Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 682
LaserBeak Avatar asked Oct 04 '11 02:10

LaserBeak


People also ask

How do I save changes in Entity Framework?

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.

How do I update an existing record in Entity Framework?

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.

Which function of DbContext is used to update the changes done thru entity framework to the database?

Persisting Data: Performs the Insert, Update and Delete operations to the database, based on entity states.

How does Entity Framework save data?

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.


1 Answers

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();
like image 129
Eranga Avatar answered Sep 27 '22 02:09

Eranga