[英]Entity Framework Generic insert method is inserting already existing entity again along with the new entity
I have following Insert 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)
{
// ...
}
}
}
This works as expected but when i want to insert a new entity, which has a relation to a existing entity, EF is re-inserting this relational (already existing) entity again along with the new entity. 这按预期工作,但是当我要插入与现有实体有关系的新实体时,EF会与新实体一起再次重新插入此关系(已存在)实体。
Details: I have a entity Supplier which already exists in my database. 详细信息:我的数据库中已有一个实体Supplier 。 I want to insert a new entity Product which has this existing Supplier entity as relation so i retrieve this Supplier from the database and add it to this Product Entity.
我想插入一个具有该现有供应商实体作为关系的新实体产品 ,因此我从数据库中检索了该供应商并将其添加到该产品实体中。 When i insert it using the generic method, it re-inserts this Supplier and obviously i don't want this behavior.
当我使用通用方法将其插入时,它会重新插入此Supplier,显然我不希望这种行为。
Am i doing something wrong here or is this by design and should i not use a generic insert function when having relational entities attached to my new entities? 我在这里做错什么吗?或者这是设计使然;在将关系实体附加到新实体时,我不应该使用通用插入函数吗?
Thank you for any suggestion or information! 感谢您的任何建议或信息! Kind regards
亲切的问候
EDIT: 编辑:
Product Entity: 产品实体:
// ... non relational properties
public ICollection<Price> Prices { get; set; }
public ICollection<Supplier> Suppliers { get; set; }
public ICollection<Productnumber> ProductNumbers { get; set; }
Price Entity: 价格实体:
public Product Product { get; set; }
public Supplier Supplier { get; set; }
Supplier Entity: 供应商实体:
public ICollection<Productnumber> ProductNumbers { get; set; }
public ICollection<Product> Products { get; set; }
public ICollection<Price> Prices { get; set; }
ProductNumber Entity: ProductNumber实体:
public Supplier Supplier { get; set; }
public Product Product { get; set; }
How should i proceed to insert a new product? 我应该如何继续插入新产品? Is this possible having this structure and using a Generic insert?
是否可以使用这种结构并使用通用插入?
If you want to add a new product to an existing Supplier you need to do as following: 如果要将新产品添加到现有供应商 ,则需要执行以下操作:
1- Retrieve the supplier entity, let's call it sup
1-检索供应商实体,我们称其为
sup
2- Add the new Product to it, 2-将新产品添加到其中,
sup.Product = new Product{properties
...}
3- Update the supplier entity, 3-更新供应商实体,
ctx.Entry(sup).State = EntityState.Modified;
ctx.SaveChanges();
You were adding a new supplier entity each time you were using the bool Insert<T> method
and this why you got unexpected behaviour, so just update the existing entry instead. 每次使用
bool Insert<T> method
,您都在添加一个新的供应商实体,这就是为什么您会有意外行为的原因,所以只需更新现有条目即可。
Hope this helps, 希望这可以帮助,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.