Attach already changed object to a data context

Problem:

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

All changes will lost after you save change.

Solution:

Call the SetModifiedProperty method  to notify the ObjectStateManager of the data context about the changes.

Example:

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

            newContext.SaveChanges();



Comments (1) -

9/22/2012 12:16:43 AM #

Auto Dialer System from voice2phone.com

Good day. Very nice website!!! I’ll bookmark your blog and take the feeds also. I am glad to locate numerous useful information right here within the post. Thank you for sharing.

Auto Dialer System from voice2phone.com United States