C# 如何更新导航集合属性
我只想使用Entity Framework 6更新客户和他的一个订单。我尝试了这一点,但它只更新了客户的订单,而不是他的订单:C# 如何更新导航集合属性,c#,entity-framework,C#,Entity Framework,我只想使用Entity Framework 6更新客户和他的一个订单。我尝试了这一点,但它只更新了客户的订单,而不是他的订单: Customer customer = db.Cutomers.Include(x => x.Orders).Where(y => y.Id ==1234).SingleOrDefault(); customer.Name = "Joe"; // changing the customer name customer.Order
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();
}
在进行更改后,您将加载
订单
集合,因此基本上这将覆盖您之前所做的更改。
由于您正在编辑订单
,因此必须将订单本身附加到集合中,以便对其进行更新
编辑
您需要显式地附加子项。不管怎样,最好自己做,我确信您不希望每次数据库调用都自动更新每个实体的整个实体树。Ok。我知道我应该在做更改之前从DB加载,但我不清楚您答案的第二部分。如何“将订单本身附加到集合,以便对其进行更新”。@user3237706除非发布GetCustomerFromDB
函数的代码,否则很难判断您是如何加载实体的。有关附加的含义,请参见我的编辑。我更新了代码以显示如何获得客户。我试过你的建议,但我想我还是遗漏了一些东西。@user3237706你是否删除了(e=>e.Orders)。Load()
部分?仍然存在。我添加了这个:Customer=db.Cutomers.Include(x=>x.Orders)。其中(y=>y.Id==1234)。SingleOrDefault();
db.Orders.Attach(customer.Orders[0]);