Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does Attach() do in Entity Framework? [duplicate]

Possible Duplicate:
Entity Framework 4 - AddObject vs Attach

I've seen the use of attach a few times, especially when manipulating models.

using (var context = new MyEntities()) {     context.Attach(client);     context.SaveChanges(); } 

From the context it looks like it just runs an UPDATE against a record in EntityFrameworks, but I also see it used in DELETE statements. So I can only assume it just gets a pointer to the database?

Could someone point me in the right direction, I've googled it for a while and whilst I don't come up empty, I can't find any good explinations of what it does (from an overview, and internally).

like image 711
John Mitchell Avatar asked Jul 29 '12 12:07

John Mitchell


People also ask

What is use of attach in entity Framework?

Attach is used to repopulate a context with an entity that is known to already exist in the database. SaveChanges will therefore not attempt to insert an attached entity into the database because it is assumed to already be there.

What does Dbcontext attach do?

Attach(Object)Begins tracking the given entity and entries reachable from the given entity using the Unchanged state by default, but see below for cases when a different state will be used. Generally, no database interaction will be performed until SaveChanges() is called.

What is Attach Method C#?

Attach is used to attach an object or the top-level object in an object graph.


1 Answers

Just as a point of interest the code you have posted does nothing

using (var context = new MyEntities()) {     context.Attach(client);     context.SaveChanges(); } 

All this does is attach the entity to the tracking graph make no modifications to the entity and save it.

Any changes made to the object before attach are ignored in the save

What would be more interesting is if it actually updated a property ie:

using (var context = new MyEntities()) {     context.Attach(client);     client.Name = "Bob";     context.SaveChanges(); } 
like image 148
Not loved Avatar answered Sep 24 '22 10:09

Not loved