44

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

Community
  • 1
  • 1
John Mitchell
  • 9,653
  • 9
  • 57
  • 91
  • See [this question](http://stackoverflow.com/q/3920111/406903) and accepted answer about `Attach` and `AddObject`. – hmqcnoesy Jul 29 '12 at 12:37

1 Answers1

64

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();
}
undefined
  • 33,537
  • 22
  • 129
  • 198
  • 1
    Interesting, I see that it only changes after its been attached. Sorry for a the tiny tangent, is there a nice clean way to edit a existing record with you already have a modified class (where the ID is the same)? Sort of an "update everything that's changed" method? – John Mitchell Jul 29 '12 at 12:45
  • 1
    This depends on the change tracking method a little but with snapshot tracking (which you are almost certaintly using) the best way to do this is by setting the dirty flag on the entity ladislav touches on how to do this here, http://stackoverflow.com/a/6829996/1070291 but you probably want to do it on the entity not the properties – undefined Jul 29 '12 at 12:52
  • 29
    @JohnMitchell After you attach an existing entity you can set its changed-state to modified, e.g. `context.Entry(client).State = EntityState.Modified; ` – devlord May 08 '15 at 23:26