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項目? –
如果你想以一種通用的方式清除所有收集項目,你可以看一看反射,但我認爲'清除這個實體的所有收集項目'函數會有點危險:)你還必須包括所有的加載泛型實體時的集合,這可能意味着加載整個數據庫。 –