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();



Using Database Initializers and seeding

Add the following code in global.asax.cs

protected void Application_Start()     
{
        Database.SetInitializer(new MyStoreDbInitializer());
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);     
}

Create the following class

public class MyStoreDbInitializer : DropCreateDatabaseAlways<MyStoreDB>    
 {
         protected override void Seed(MusicStoreDB context)
         {
             context.Artists.Add(new Artist {Name = “Al Di Meola”});
             context.Genres.Add(new Genre { Name = “Jazz” });
             context.Albums.Add(new Album
                                 {
                                     Artist = new Artist { Name=”Rush” },
                                     Genre = new Genre { Name=”Rock” },
                                     Price = 9.99m,
                                     Title = “Caravan”
                                 });
             base.Seed(context);
         }
     }