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();
In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction. The following example demonstrates this.
We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to is to attach/add it to the context.
Persisting Data: Performs the Insert, Update and Delete operations to the database, based on entity states.
Insert Data Add methods add a new entity to a context (instance of DbContext) which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students. Add(std) adds a newly created instance of the Student entity to a context with Added EntityState.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With