2009-01-11 53 views
4

我想做一個簡單的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. 
    } 
} 

我假設我需要先保存的產品我嘗試之前,並保存順序?我很困惑:(

回答

-1
+0

感謝您的鏈接。您絕對正確的看到M-M在LINQ2SQL中沒有(本機)支持,並且1-M:M-1橋是常規方法。不太確定是否有回票。 – 2010-12-29 08:25:49

2
// Associate each product to the a new order_detail. 
orderDetailList.Add(new Order_Detail 
{ 
    Product = new SqlContext.Product 
    { 
     Foo = product.Foo 
    } 
}); 

這裏有一點是錯誤的,那就是你創建了一個新的產品來設置你的Order_Detail.Product屬性。相反,您應該從數據庫中提取產品並將其設置在屬性上。

我不確定order.ProductList裏面有什麼 - 如果這些產品是從數據庫加載的,那麼你應該將它們直接設置到你的Order_Detail.Product,而不是做新的SqlContext.Product。

@jfar L2S不支持許多一對多的關係,你不能對你的訂單屬性的產品(在這種情況下,這其實是一件好事,因爲訂單明細有數量和其他屬性)。

+0

我其實並不認同它「支持m2m」。關於任何其他O/R映射器的好處是,您可以完全按照您提及的橫向(兩種方式)進行操作。 User.Roles.Add(SomeRole),給定典型的user-user_role-role方案。 1..n Northwind中的關係很好,但是當你想要超越(並且你幾乎總是必須)時,Linq2SQL會非常短。 – 2009-10-27 15:46:08