【发布时间】:2017-06-09 14:25:54
【问题描述】:
我首先使用了实体框架代码。我有 3 个表。我的桌子是:
-Product :{name id ...}
-property :{name id }
-productProperty:{productId propertyId value}
知道当我编辑我的产品时,我想向该产品添加新属性。 所以我的代码是:
listProducts.Remove(curentProduct);
curentProduct.productName = txtname.Text;
curentProduct.ProductImage = BitmapSourceToByteArray((BitmapSource)imgPhoto.Source);
curentProduct.Cat = findCategory(cbCatnewpro.SelectedItem.ToString());
curentProduct.productCode = txtProductCode.Text;
curentProduct.productInfo = txtInfo.Text;
curentProduct.productPrice = txtPrice.Text;
curentProduct.productTEdada = Convert.ToInt32(txtTedad.Text);
List<dginfocomper> list = new List<dginfocomper>();
for (int i = 0; i < dgPro.Items.Count; i++)
{
dginfocomper d = dgPro.Items[i] as dginfocomper;
list.Add(d);
}
foreach (var item in list)
{
if (item == null)
break;
foreach (var item1 in curentProduct.ProductsProperties.ToList())
{
int id = findpropertyId(item.m0);
if (id == item1.propertyID)
{
item1.value = item.m1;
break;
}
}
}
int y = list.Count - curentProduct.ProductsProperties.ToList().Count;
int x = curentProduct.ProductsProperties.ToList().Count - 1;
for (int i = 0; i < y-1; i++)
{
ProductProperty pp = new ProductProperty();
pp.propertyID = findpropertyId(list[x].m0);
pp.value = list[x].m1;
curentProduct.ProductsProperties.Add(pp);
x--;
}
listProducts.Add(curentProduct);
entity.SaveChanges();
dgRowProFill(curentProduct);
MessageBox.Show("با موفقیت ثبت شد");
但我得到以下错误:
{"违反 PRIMARY KEY 约束 'PK_dbo.ProductProperties'。无法在对象 'dbo.ProductProperties' 中插入重复键。重复键值为 (1, 7)。\r\n语句已终止。"}
我在谷歌上搜索但我找不到我的问题。那么我该如何解决它?
【问题讨论】:
-
您是否尝试过在重新添加之前从数据库中删除curentProduct(并保存您的更改)?
-
数据库告诉您,您正在插入与现有 ProductProperty 具有相同主键的 ProductProperty。不确定您的代码有什么问题,如果有的话。
标签: c# wpf entity-framework code-first