【发布时间】:2019-04-17 05:16:20
【问题描述】:
我有以下插入方法:
public static bool Insert<T>(T item) where T : class
{
using (ApplicationDbContext ctx = new ApplicationDbContext())
{
try
{
ctx.Set<T>().Add(item);
ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// ...
}
}
}
这按预期工作,但是当我想插入一个与现有实体有关系的新实体时,EF 将再次插入这个关系(已经存在的)实体以及新实体。
详情: 我的数据库中已经存在一个实体 Supplier。 我想插入一个新实体 Product ,它具有这个现有的供应商实体作为关系,所以我从数据库中检索这个供应商并将它添加到这个产品实体。当我使用通用方法插入它时,它会重新插入这个供应商,显然我不想要这种行为。
我在这里做错了什么还是设计使然,当将关系实体附加到我的新实体时,我不应该使用通用插入函数吗?
感谢您的任何建议或信息! 亲切的问候
编辑:
产品实体:
// ... non relational properties
public ICollection<Price> Prices { get; set; }
public ICollection<Supplier> Suppliers { get; set; }
public ICollection<Productnumber> ProductNumbers { get; set; }
价格实体:
public Product Product { get; set; }
public Supplier Supplier { get; set; }
供应商实体:
public ICollection<Productnumber> ProductNumbers { get; set; }
public ICollection<Product> Products { get; set; }
public ICollection<Price> Prices { get; set; }
ProductNumber 实体:
public Supplier Supplier { get; set; }
public Product Product { get; set; }
我应该如何继续插入新产品?这可能具有这种结构并使用通用插入吗?
【问题讨论】:
标签: c# entity-framework insert duplicates relational-database