Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Update Entity by Replacing in EF?

I have a class Order which has a List<Item> and a Customer. I need to update Order and its child class. First I only attach the Order object but in this way EF cannot Understand changes in Items and Customers.

Then I tried changing the state of the child classes to EntityState.Modified but that didn't work either.Is there a way in EF to replac parent and child classes with existing record in db?

And if there isn't, how can I solve this problem?

var temp = db.Orders.Find(order.Id);
temp = order;
temp.Items = order.Items;
temp.Customer = order.Customer; 
db.SaveChanges(); 

i try this too after changing Order in user actions:

db.Orders.Attach(order) ;
db.SaveChanges();
like image 686
Navid_pdp11 Avatar asked Apr 01 '16 08:04

Navid_pdp11


People also ask

How do you update an Entity Framework?

The steps to update an existing entity are quite simple. First retrieve an instance of the entity from the EntitySet<T> (in our case ObjectSet<Customer>), then edit the properties of the Entity and finally call SaveChanges() on the context.


2 Answers

I haven't tried this for Entities with Child classes but you could try setting the value.

context.Entry(temp).CurrentValues.SetValues(order);
context.SaveChanges();

This assumes that order is an instance of the Entity Orders. Note this will completely overwrite every property of the temp record with that of order.

This blog has more information (Also applies to EF Core): https://web.archive.org/web/20191225092110/http://kerryritter.com/updating-or-replacing-entities-in-entity-framework-6/

like image 63
Dale C Avatar answered Oct 04 '22 05:10

Dale C


If you want to replace entity with related/child/nested references and collections you can use Tracked Graph since EF Core 2.2. All entities IDs should be database generated.

Add method to your context

public void Replace<TEntity>(TEntity oldEntity, TEntity newEntity) where TEntity : class
{
    ChangeTracker.TrackGraph(oldEntity, e => e.Entry.State = EntityState.Deleted);
    ChangeTracker.TrackGraph(newEntity, e => e.Entry.State = e.Entry.IsKeySet ? EntityState.Modified : EntityState.Added);
}

Usage

var oldOrder = db.Orders
        .AsNoTracking()
        .Include(o => o.Items)
        .Include(o => o.Customer)
        .Find(newOrder.Id);

db.Replace(oldOrder, newOrder);

db.SaveChanges();

Note that old entity should be detatched using AsNoTracking or

db.Entry(oldOrder).State = EntityState.Detached;
like image 39
Demonel Avatar answered Oct 04 '22 04:10

Demonel