【问题标题】:C# Entityframework saving record with many to many navigation property具有多对多导航属性的 C# Entity Framework 保存记录
【发布时间】:2016-03-06 17:43:08
【问题描述】:

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

customer、shoppinglist、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) 如果我想在客户购物清单项目中添加新项目,我应该怎么做?

【问题讨论】:

    标签: c# mysql entity-framework


    【解决方案1】:

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

    像这样:

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

    【讨论】:

    • 具有相同 id (-1) 的对象是 ShoppingList 而不是 Item。当我附加该项目时,我试图告诉它该项目存在于数据库中,因此当它添加 shoppingList 对象时,他应该将 shoppingList 对象项目连接到数据库中的现有项目(即更新 shoppinglist_item 表但不项目表)。
    • 您是说购物清单中的所有物品在添加到 objectstatemanager 时都没有 ID 0 吗?
    • 是的,每个都有唯一的 id(提供给上述函数的客户是从数据库复制然后编辑的 - 每次编辑都会导致 id 更改为 0 - 这样我就可以判断我是否需要添加新的或将其连接到现有的)
    • 因此错误可能来自购物清单具有相同项目的事实,然后您将其附加到相同的上下文中。所以你有3个购物清单多次附加相同的ID?关键是有一个上下文来处理所有这些问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2023-01-30
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多