Home » c# » What exactly does Attach() do in Entity Framework? [duplicate]

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

Posted by: admin February 22, 2018 Leave a comment

Questions:

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

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();
}