Attach already changed object to a data context in Entity FrameworkPosted in ADO.NET, Entity Framework by Branislav Abadjimarinov on 12/12/2009 12:38:00 AM - CST
Entity Framework in its current version (.net 3.5 sp 1) has some
problems with multi-tier application architecture. If you need to
use different data context instances for getting an object and
submitting the changes made to it you'll face some frustration.
Typical scenario in n-tier applications is to use one data context
for selecting data and another for submitting the changes made. The
problem is that once you attach an object to the new context
you'll lose tracking of all changes made to the object.
The solution is to explicitly call the SetModifiedProperty method to notify the ObjectStateManager of the data context about the changes. Also you should be aware that the property's state is set with reflection (when you need to specify a method or class name as string usually reflection is involved (-: )
AdventureWorksLTEntities context = new AdventureWorksLTEntities();
Product product = context.ProductSet.FirstOrDefault();
if (product != null)
product.ListPrice += 10; // product.EntityState is set to Modified
AdventureWorksLTEntities newContext = new AdventureWorksLTEntities();
context.Detach(product); // product.EntityState is set to Detached
newContext.Attach(product); // product.EntityState is set to Unchanged
ObjectStateEntry state = newContext.ObjectStateManager.GetObjectStateEntry(product);
state.SetModifiedProperty("ListPrice"); // product.EntityState is set to Modified
P.S. Special thanks for this post to the ADO.NET team from Microinvest for introducing this problem to me.