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
    }
});

ここで間違っていることの1つは、Order_Detail.Productプロパティに設定する新しい製品を作成することです。代わりに、データベースから取得する製品を取得して、プロパティに設定する必要があります。

order.ProductListの内部がわかりません。これらの商品がデータベースから読み込まれる場合は、新しいSqlContext.Productを実行するのではなく、Order_Detail.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

データベーススキーマの写真が記事の1つと同じであることは奇妙です...

于 2009-01-11T05:46:09.280 に答える