If I have use database first to build a context, and instantiate this context twice. I want to query a specific entity from the first context and add it to the second context, what’s the different between using AddObject and Attach.
eg.
Student stu = context1.Students.First();
context1.Detach(stu);
context2.Attach(stu);
and
Student stu = context1.Students.First();
context1.Detach(stu);
context2.Students.AddObject(stu);
What’s the difference between them?
Thanks in advance!
The Attach method will attach the object or object graph in Unchanged state. That means if you don’t do any modifications to the object after you attach it, EF will not issue any Update/Delete commands for that object when you call
SaveChanges()method.But when you use
AddObjectmethod EF will insert the object as a new entity inSaveChanges()method.If the
context2is connected to a different database and you want to copy the instance then you can useAddObject. Otherwise use theAttachmethod.