4

我正在尝试做一个简单的 linq 2 sql 多对多,插入一些数据,操作。

这是代表多对多的股票 Northwind 模型:

替代文字 http://www.iaingalloway.com/images/linq-detail.jpg

现在我要做的是插入一个新订单,如果产品不存在,那么在同一交易中同时插入该产品。我得到的错误是:

System.Data.Linq.DuplicateKeyException: Cannot add an entity with a
 key that is already in use.

所以这是我的(伪)代码:

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.
    }
}

我假设我需要先保存产品,然后再尝试保存订单?我很混乱 :(

4

2 回答 2

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 确实支持多对多关系,您的订单上不能有属性 Products(在这种情况下,这实际上是一件好事,因为 OrderDetails 具有 Quantity 和其他属性)。

于 2009-01-11T06:40:05.397 回答
-1

Linq2Sql 不支持多对多关系。:(

有几个解决方法:

http://www.iaingalloway.com/many-to-many-relationships-in-linq-to-sql

http://blogs.msdn.com/mitsu/archive/2008/03/19/how-to-implement-a-many-to-many-relationship-using-linq-to-sql-part-ii-add-删除-support.aspx

奇怪的是您的数据库架构的图片与其中一篇文章相同......

于 2009-01-11T05:46:09.280 回答