Saving changes/updating existing object in dataset with Entity FrameWork and not have to set each property individually

12,845

You can attach the existing product and set its state as Modified.

If you are using DbContext API

context.Products.Attach(product);
context.Entry(product).State = EntityState.Modified;

context.SaveChanges();

For ObjectContext

context.Products.Attach(product);
context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified);

context.SaveChanges();
Share:
12,845

Related videos on Youtube

LaserBeak
Author by

LaserBeak

Updated on June 05, 2022

Comments

  • LaserBeak
    LaserBeak almost 2 years

    Can I do something like the below (which does not work) without having to explicitly set each property of the object. Product is the object that is created by the default model binder from a form submission and ProductInDb is object in the context/database that I wish to override/update. The ProductID primary key is the same on both.

    var ProductInDb = context.Products.FirstOrDefault(x => x.ProductID == product.ProductID);
    
    ProductInDb = product;
    
    context.SaveChanges();
    
  • Elad Benda
    Elad Benda about 11 years
    @Eranga please see my following question: stackoverflow.com/questions/16085654/…
  • Elad Benda
    Elad Benda about 11 years
    @Eranga I have tried the same thing, but got uniquness violation error in the DB as I edit an already exiting entity. Maybe your syntax will help me.