10

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

1 Answer 1

19

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();
Sign up to request clarification or add additional context in comments.

4 Comments

Does not contain a definition for "Entry". Do I need to reference something ? Already using System.Data.Objects; What else ? Pressing ctrl + . gives nothing for Entry.
@LaserBeak It looks like you are using ObjectContext. See my updated answer.
@Eranga please see my following question: stackoverflow.com/questions/16085654/…
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.