2009-01-11 51 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