1
我先使用EF 4.1代码,并且在更新Order实体时出现问题,当现有实体包含OrderList的非空集合并且用户已经删除了一些现有的添加了一个新的订单列表。使用ICollection导航属性更新使用EF 4.1代码的实体首先
我的域模型如下图所示
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;}
}
这是我使用了更新Order实体的代码。
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代码优先?
感谢 大师
谢谢Wouter。这可以通过存储库模式来实现吗?我正在访问多个实体(在本例中为context.Orders和context.OrderLists)。 Order实体中可能还有更多的ICollection项目? –
如果你想以一种通用的方式清除所有收集项目,你可以看一看反射,但我认为'清除这个实体的所有收集项目'函数会有点危险:)你还必须包括所有的加载泛型实体时的集合,这可能意味着加载整个数据库。 –