[英]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 。 我想插入一个具有该现有供应商实体作为关系的新实体产品 ,因此我从数据库中检索了该供应商并将其添加到该产品实体中。 当我使用通用方法将其插入时,它会重新插入此Supplier,显然我不希望这种行为。
我在这里做错什么吗?或者这是设计使然;在将关系实体附加到新实体时,我不应该使用通用插入函数吗?
感谢您的任何建议或信息! 亲切的问候
编辑:
产品实体:
// ... 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-将新产品添加到其中,
sup.Product = new Product{properties
...}
3-更新供应商实体,
ctx.Entry(sup).State = EntityState.Modified;
ctx.SaveChanges();
每次使用bool Insert<T> method
,您都在添加一个新的供应商实体,这就是为什么您会有意外行为的原因,所以只需更新现有条目即可。
希望这可以帮助,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.