我想做一個簡單的LINQ 2多對多sql,插入一些數據,操作。問題與Linq2Sql多對多的關係和插入新的對象
這裏是代表一個多對多的股票羅斯文模型:
alt text http://www.iaingalloway.com/images/linq-detail.jpg
現在我想要做的是插入一個新的秩序,如果產品不存在,然後插入在同一時間內,在同一交易。我得到的錯誤是:
System.Data.Linq.DuplicateKeyException: Cannot add an entity with a
key that is already in use.
所以這是我(pseduo)代碼:
using (SqlContext db = new SqlContext())
{
// Get existing or create a new instance.
Order newOrder = GetOrder(order.Id) ?? new Order();
// Left to right stuff.
newOrder.Foo = order.Foo;
// Now associate this new order to a product (which might not exist).
if (!order.ProductList.IsNullOrEmpty())
{
// We have some products...
IList<Order_Detail> orderDetailList = new List<Order_Detail>();
foreach(Models.Product product in order.ProductList)
{
// Associate each product to the a new order_detail.
orderDetailList.Add(new Order_Detail
{
Product = new SqlContext.Product
{
Foo = product.Foo
}
});
}
// Now associate all the order_details to this order.
newOrder.Order_Details.AddRange(orderDetailList);
if (newOrder.Id <= 0)
db.InsertOnSubmit(newOrder);
db.SubmitChanges(); // <-- exception throw here.
}
}
我假設我需要先保存的產品我嘗試之前,並保存順序?我很困惑:(
感謝您的鏈接。您絕對正確的看到M-M在LINQ2SQL中沒有(本機)支持,並且1-M:M-1橋是常規方法。不太確定是否有回票。 – 2010-12-29 08:25:49