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).
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.
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.
Attach is used to attach an object or the top-level object in an object graph.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With