具有多对多导航属性的C#Entityframework保存记录

时间:2016-03-06 08:50:26

标签: c# mysql entity-framework

我正在使用ADO.NET(来自mysql db)创建我的模型。我有6张桌子:

客户,购物清单,customer_shoppinglist(其中有两个FK用于customerid,另一个用于shoppinglist id),item和shoppinglist_item表(有两个FK用于shoppinglist id,另一个用于item id)

每个购物清单都包含一个项目列表 - 每个项目都可以与多个购物清单相关联。

每个客户都包含一个购物清单列表 - 每个购物清单都可以与多个客户相关。

现在我有两个问题:

1)我想添加一个有3个购物清单的新客户。数据库中存在的数据库和两个包含项目列表中现有项目的新项目。 这是我的代码(如果我只向客户添加一个新的购物清单,则效果很好):

    public static void saveCustomer(Customer customer){
          using (var context = new DBContext()) {
                Customer customerToAdd= new Customer(customer);
                foreach (ShoppingList shoppingList in customer.shoppingLists) {
                    if (shoppingList .id == 0) {
                        customerToAdd.shoppingLists.Add(new ShoppingList(shoppingList));
                    }
                    else
                        customerToAdd.shoppingLists.Add(shoppingList);
                }

                foreach (ShoppingList shoppingList in customer.shoppingLists) {
                    foreach(Item item in shoppingList.items){
                        context.items.Attach(item);
                    }
                    if (shoppingList.id != -1) {
                        context.shoppingLists.Attach(shoppingList);
                    }
                }
                context.customers.Add(customerToAdd);
                context.SaveChanges();
            }
     }

并且

 public ShoppingList(ShoppingList oShoppingList) {
        this.id = -1;
        this.name = oShoppingList.name;
        this.description = oShoppingList.description;
    }

(调用函数时,customer中的新购物清单id = 0)

我收到此错误:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

在线:

context.items.Attach(item);

2)如果我想在客户购物清单项目中添加新商品,该怎么办?

1 个答案:

答案 0 :(得分:0)

这是因为您将具有相同ID的对象附加到上下文(0 / -1)。 你可以通过创建一个单独的函数来解决这个问题,该函数创建一个DbContext,附加并保存然后杀死上下文。

像这样:

   public bool addShoppingItem(Item item){
           using (var context = new DBContext()) 
           {
            context.items.Add(item);
            context.SaveChanges();
           }
   }