user3237706
user3237706

Reputation: 3

How to update a navigation collection property

I simply would like to update the customer and one of his orders using Entity Framework 6. I tried this but it is updating the customer only not his orders:

Customer customer = db.Cutomers.Include(x => x.Orders).Where(y => y.Id  ==1234).SingleOrDefault();
customer.Name = "Joe";              //  changing the customer name
customer.Orders[0].OrderDesc = "NewDesc";  //  changing one of the orders
customer.Orders[0].OrderDate = DateTime.Now;

using (var db = new Context())
{      
       db.Cutomers.Attach(customer);
       db.Entry(customer).Collection(e => e.Orders).Load();
       db.Entry(customer).State = EntityState.Modified;   
       db.SaveChanges();
}

Upvotes: 0

Views: 119

Answers (2)

Adam Heeg
Adam Heeg

Reputation: 1714

You need to explicitly attach the children. It is better to do this yourself anyway, i'm sure you don't want every database call to automatically update the entire entity tree for each entity.

Upvotes: 0

SOfanatic
SOfanatic

Reputation: 5573

You are loading the Orders collection after making the changes so basically this is overriding the changes you previously made. Since you are editing the Order you are going to have to Attach the order itself to the collection so that it is updated.

EDIT

db.Orders.Attach(customer.Orders[0]);

Upvotes: 1

Related Questions