【发布时间】: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