2016-03-06 38 views
0

我使用ADO.NET(从MySQL数据库)创建我的模型。我有6个表格:许多导航属性的C#Entityframework保存记录

customer,shoppinglist,customer_shoppinglist(它有两个FK一个用于customerid,另一个用于shoppinglist id),item和一个shoppinglist_item表(它有两个FK一个用于购物单id,另一个用于物品ID)

每个购物清单都包含物品清单 - 并且每个物品可以与多个购物清单相关联。

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

现在我有2个问题:

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

(客户新的购物清单具有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)如果要将新项目添加到客户购物清单项目,应该怎么做?

回答

0

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

像这样:

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

具有相同的ID(-1)的对象是ShoppingList没有项目。当我附加项目时,我试图告诉它,这个项目存在于数据库中,因此当它添加shoppingList对象时,他应该将shoppingList对象项目连接到数据库中的现有项目(即更新shoppinglist_item表,但不会项目表)。 –

+0

当你将它们添加到objectstatemanager时,你是否说购物清单中的所有商品都没有ID 0? – misha130

+0

是的,每个都有唯一的ID(给予上述功能的客户从数据库中复制,然后进行编辑 - 每次编辑都会导致ID变为0 - 这样我可以判断是否需要添加新的或连接它到现有的) –