如何控制EF插入数据库?

时间:2016-10-12 07:08:36

标签: c# database entity-framework

我有3个表GoodsProducerCategoriesProducerCategoriesGoods有一对多的关系,我有一个通用的插入方法,代码如下所示。

问题在于,当我尝试插入商品列表时,首先正确添加商品,但如果下一个品牌具有相同ID的类别,则会抛出关于主键的例外。

但是我想控制插入类似的东西,每次插入表CategoriesProducer之前检查,如果行已经存在,只需更新它,例如或跳过。

代码与模型和我的通用插入这里:

public class Good
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

    public virtual Category Category { get; set; }
    public virtual Producer Producer { get; set; }

    public override string ToString()
    {
        return Id + "/" + Name + "/" + Price + "/" + Category.Name + "/" + Producer.Name + "/" + Producer.Country;
    }
}

public class Producer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }

    public virtual ICollection<Good> Goods { get; set; }

    public override string ToString()
    {
        return Id + "/" + Name + "/" + Country;
    }
}

public class Category
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Good> Goods { get; set; }

    public override string ToString()
    {
        return Id + "/" + Name;
    }
}

public void AddList(List<T> collection, DbContext GoodsContext)
{
        foreach (var item in collection)
        {
            GoodsContext.Set<T>().Add(item);
            GoodsContext.SaveChanges();
        }
}

1 个答案:

答案 0 :(得分:1)

您可以使用新发布的EntityGraphOperations实体框架代码优先轻松实现此目的。我已将其发布在githubcode-projectnuget中。借助InsertOrUpdateGraph方法,它会自动将您的实体设置为AddedModified

 foreach (var item in collection)
 {
        // This will set the state of the main entity and all of it's navigational 
        // properties as `Added` or `Modified`.
        GoodsContext.InsertOrUpdateGraph(item);
        GoodsContext.SaveChanges();

        GoodsContext.Entry(item).State = EntityState.Detached;
 }

您可以通过逐步演示阅读my article on Code-project,并准备下载示例项目。