Entity Framework 4: Mastering AddObject
and Attach
Effective use of Entity Framework hinges on understanding the distinct roles of ObjectSet.AddObject
and ObjectSet.Attach
. While AddObject
inserts new entities, Attach
manages existing ones. However, the situations requiring Attach
can be nuanced.
One key use case for Attach
involves entities detached from the context. This often occurs after retrieving an entity and subsequently closing the context. To re-engage this entity for modification, use Attach
:
var existingPerson = new Person { Name = "Joe Bloggs" };
ctx.Persons.Attach(existingPerson);
existingPerson.Name = "Joe Briggs";
ctx.SaveChanges();
This generates an UPDATE
statement, avoiding a redundant database retrieval.
Another valuable application of Attach
is connecting existing, context-attached entities that lack automatic relationships. Consider a Person
entity with an Addresses
navigation property (a collection of Address
entities). If you've loaded both Person
and Address
objects but their relationship isn't established, Attach
provides the solution:
var existingPerson = ctx.Persons.SingleOrDefault(p => p.Name == "Joe Bloggs");
var myAddress = ctx.Addresses.First(a => a.PersonID != existingPerson.PersonID);
existingPerson.Addresses.Attach(myAddress);
ctx.SaveChanges();
Here, Attach
updates the relationship without modifying the entities themselves.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3