首先使用 EF 4.1 代码更新具有 ICollection 导航属性的实体
我首先使用 EF 4.1 代码,当现有实体包含 OrderList 的非空集合并且用户删除了一些现有实体并添加了新的订单列表时,更新 Order 实体时遇到问题。
我有如下所示的域模型
public class Order
{
public int Id { get; set;
public string Name { get; set;}
public ICollection<OrderList> OrderLists { get; set;}
}
public class OrderList
{
public int Id { get; set;}
public int OrderId { get; set;}
public string ItemDescription { get; set;}
public decimal Price { get; set;}
public virtual Order Order { get; set;}
}
这是我用于更新订单实体的代码。
using (var context = new MyDbContext())
{
var order = context.Orders
.Include("OrderLists")
.FirstOrDefault(o => o.Id == orderId);
order.Name = "New name"; // this gets saved
order.OrderLists.Clear(); // Does not delete the existing order list items
order.OrderLists = new List<OrderList> { new OrderList { OrderId = order.Id, ItemDescription = "New Item" } }; // Does not create new list
context.Orders.Attach(order);
context.Entry<Order>(order).State = System.Data.EntityState.Modified;
context.ChangeTracker.DetectChanges();
context.SaveChanges();
}
请指导我如何首先使用 EF 4.1 代码实现此目的?
谢谢 大师
I am using EF 4.1 code first and have problem updating Order entity, when the existing entity contains a not null collection of OrderList and user has removed a few of the existing and added a new order list.
I have the domain model as shown below
public class Order
{
public int Id { get; set;
public string Name { get; set;}
public ICollection<OrderList> OrderLists { get; set;}
}
public class OrderList
{
public int Id { get; set;}
public int OrderId { get; set;}
public string ItemDescription { get; set;}
public decimal Price { get; set;}
public virtual Order Order { get; set;}
}
This is the code i am using for updating the Order entity.
using (var context = new MyDbContext())
{
var order = context.Orders
.Include("OrderLists")
.FirstOrDefault(o => o.Id == orderId);
order.Name = "New name"; // this gets saved
order.OrderLists.Clear(); // Does not delete the existing order list items
order.OrderLists = new List<OrderList> { new OrderList { OrderId = order.Id, ItemDescription = "New Item" } }; // Does not create new list
context.Orders.Attach(order);
context.Entry<Order>(order).State = System.Data.EntityState.Modified;
context.ChangeTracker.DetectChanges();
context.SaveChanges();
}
Please some guide me on how I can acheive this using EF 4.1 code first?
Thanks
Guru
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以解决问题:
您需要单独删除订单列表项,然后清除集合。
This should do the trick:
You need to delete the orderlist items individually and then clear the collection.