Saving changes / updating an existing object in a dataset using Entity FrameWork and it is not necessary to set each property separately

Can I do something like below (which does not work) without explicitly setting each property of the object. A product is an object that is created by the default binder from the form view, and ProductInDb is an object in the context / database that I want to override / update. The primary key ProductID is the same for both.

var ProductInDb = context.Products.FirstOrDefault(x => x.ProductID == product.ProductID); ProductInDb = product; context.SaveChanges(); 
+6
source share
1 answer

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

If you are using the 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(); 
+13
source

Source: https://habr.com/ru/post/898559/


All Articles