通用插入多对多(实体框架)

时间:2018-08-17 07:27:32

标签: entity-framework duplicates many-to-many generic-programming

我正在尝试使用一种按预期工作的通用方法插入新实体(产品)。该实体(产品)有另一个实体(供应商),当我尝试将此同一个产品插入与之相关的新供应商(aka 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
}

我有一个使用Fluent API的带有SupplierId和ProductId的ProductSupplier表。 在这种情况下,我仍然可以使用我的通用插件吗?如果是,我做错了什么,怎么做错了,为什么我从数据库获得的供应商会被重新插入?

谢谢大家的反馈! 问候

更新: 我认为这是由于我在执行CRUD操作时将上下文封装在using语句中。我遇到了THIS POST

下周我将看一下,因为我必须实现其他功能。同时随意添加您的2美分:)

更新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;                              
        }
    }

1 个答案:

答案 0 :(得分:0)

我已经尝试了几种方法,但是到目前为止只有一种方法有效,因此我将继续进行这种方法,但是请随时发表您的(更好的)建议,以便我也许可以改进当前的解决方案。我的工作非常简单,我很确定必须有其他方法,但目前还不了解它们。每当我创建新实体时,在进行任何插入/更新之前,如果存在相关实体,我都会获取相关实体并将其附加到实体中进行插入,如果不存在,则实体会为我插入它们。

希望这对任何人都有帮助。 问候