【发布时间】:2019-07-05 17:35:30
【问题描述】:
我正在尝试使用按预期工作的通用方法插入一个新实体(产品)。该实体(产品)有另一个实体(供应商),当我尝试将同一产品与与之相关的新供应商(又名 Product.Suppliers.Add(NewSupplier))插入时,它会重新插入已经存在的产品(使用播种器方法)到数据库中...我知道它与供应商有关,因为当我不添加它并简单地插入产品并且不与同一供应商创建副本时。
这里有更多(简化的)信息: 产品实体:
public class Product : BaseEntity
{
public string ProductName { get; set; }
public virtual ICollection<Supplier> Suppliers { get; set; }
... others
}
供应商实体:
public class Supplier:BaseEntity
{
public string SupplierName { get; set; }
public virtual ICollection<Product> Products { get; set; }
... others
}
我有一个 ProductSupplier 表,其中包含使用 Fluent API 的 SupplierId 和 ProductId。 在这种情况下我仍然可以使用我的通用插入吗?如果可以,我做错了什么以及我做错了什么,为什么我从数据库获得的供应商被重新插入?
感谢大家的任何反馈! 亲切的问候
更新: 我认为这是因为我在执行 CRUD 操作时将上下文封装在 using 语句中。我遇到过THIS POST
下周我会看看,因为我必须实现其他功能。同时随意添加您的 2cents :)
更新 2
这是我的通用插入方法:
public static bool Insert<T>(T item) where T: class // here we specify that the <T> object is of type 'class'
{
using (ApplicationDbContext ctx = new ApplicationDbContext())
{
ctx.Database.Log = (dbLog => logger.Debug(dbLog));
ctx.Set<T>().Add(item);
ctx.SaveChanges();
return true;
}
}
【问题讨论】:
-
我查看了几个来源,我怀疑该怎么做。例如:stackoverflow.com/questions/11646299/…,我想知道我是否应该只使用 1 个 DbContext,或者将它传递给它,或者只是不将我的 Context 操作放在 using 语句中,这样它就不会关闭,我是否应该从 DB 获取相关实体插入与其相关的新记录并将它们链接/附加到彼此并插入新实体?请注意,我使用的是通用插入/更新方法。有人有建议吗?谢谢!
-
有人请:s?谢谢
标签: entity-framework duplicates many-to-many generic-programming