[英]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.