Entity Framework 通用插入方法正在将现有实体与新实体一起再次插入
Entity Framework Generic insert method is inserting already existing entity again along with the new entity
我有以下插入方法:
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,它有这个现有的 Supplier 实体作为关系,所以我从数据库中检索这个 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; }
我应该如何继续插入新产品?这可能具有这种结构并使用通用插入吗?
如果您想向现有 供应商 添加新产品,您需要执行以下操作:
1- 检索供应商实体,我们称之为 sup
2- 添加新的 Product,
sup.Product = new Product{properties
...}
3- 更新 供应商 实体,
ctx.Entry(sup).State = EntityState.Modified;
ctx.SaveChanges();
您每次使用 bool Insert<T> method
时都在添加一个新的供应商实体,这就是您出现意外行为的原因,因此只需 更新 现有条目即可。
希望这对您有所帮助,
我有以下插入方法:
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,它有这个现有的 Supplier 实体作为关系,所以我从数据库中检索这个 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; }
我应该如何继续插入新产品?这可能具有这种结构并使用通用插入吗?
如果您想向现有 供应商 添加新产品,您需要执行以下操作:
1- 检索供应商实体,我们称之为 sup
2- 添加新的 Product,
sup.Product = new Product{properties
...}
3- 更新 供应商 实体,
ctx.Entry(sup).State = EntityState.Modified;
ctx.SaveChanges();
您每次使用 bool Insert<T> method
时都在添加一个新的供应商实体,这就是您出现意外行为的原因,因此只需 更新 现有条目即可。
希望这对您有所帮助,