What exactly does Attach() do in Entity Framework?

c# entity-framework

Question

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).

1
36
5/23/2017 12:02:24 PM

Accepted Answer

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();
}
52
7/29/2012 12:44:08 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow