Hi All,
I have been working with Entity Framework 4 recently, and am slightly confused as to when to use ObjectSet.Attach, and ObjectSet.AddObject.
From my understanding:
- Use "Attach" when an Entity already exists in the system
- Use "AddObject" when creating a brand new Entity
So, if i'm creating a new Person, i do this.
var ctx = new MyEntities();
var newPerson = new Person { Name = "Joe Bloggs" };
ctx.Persons.AddObject(newPerson);
ctx.SaveChanges();
If i'm modifying an existing Person, i do this:
var ctx = new MyEntities();
var existingPerson = ctx.Persons.SingleOrDefault(p => p.Name = "Joe Bloggs" };
existingPerson.Name = "Joe Briggs";
ctx.SaveChanges();
Keep in mind, this is a very simple example. In reality i am using Pure POCO's (no code generation), Repository pattern (don't deal with ctx.Persons), and Unit of Work (don't deal with ctx.SaveChanges). But "under the covers", the above is what happens in my implementation.
Now, my question - I am yet to find a scenario where i have had to use Attach.
What am i missing here? When do we need to use Attach?
EDIT
Just to clarify, i'm looking for examples of when to use Attach over AddObject (or vice-versa).
EDIT 2
The below answer is correct (which i accepted), but thought i'd add another example where Attach would be useful.
In my above example for modifying an existing Person, two queries are actually being executed.
One to retrieve the Person (.SingleOrDefault), and another to perform the UPDATE (.SaveChanges).
If (for some reason), i already knew that "Joe Bloggs" existed in the system, why do an extra query to get him first? I could do this:
var ctx = new MyEntities();
var existingPerson = new Person { Name = "Joe Bloggs" };
ctx.Persons.Attach(existingPerson);
ctx.SaveChanges();
This will result in just an UPDATE statement being executed.