插入新实体而不创建子实体(如果存在)

Insert a new entity without creating child entities if they exist

我使用代码优先的 EF,我有这样的模型:

public class Product
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public Customer Customer { get; set; }
}

public class Customer 
{
    public Customer ()
    {
        Products = new List<Product>();
    }

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

    // more stuff snipped...

    public ICollection<Product> Products{ get; set; }
}

我收到了客户 ID 以及产品 ID 列表。当数据库中没有产品时,我想添加它:

    var newProduct = new Product{ Id = id, Name = "<no name yet>", Customer = customer };
    InsertProduct(newProduct);

问题是 EF 尝试级联更改并尝试插入一个新的 Customer 对象,该对象与现有对象具有相同的 ID,因此它失败了。我该如何解决?

这是插入方法:

    public void InsertProduct(Product item)
    {
        CustomerContext.Entry(item).State = EntityState.Added;
        CustomerContext.Set<Product>().Add(item);
    }

如果给父级添加一个外键会更容易class:

public class Product
{
    ....

    public int CustomerId { get; set; }

    public Customer Customer { get; set; }
}

然后想插入的时候设置外键而不是导航属性:

    var newProduct = new Product
       { 
          Id = id, 
          Name = "<no name yet>", 
          CustomerId = customer.Id 
       };
   InsertProduct(newProduct);

参考文献:

Why does Entity Framework Reinsert Existing Objects into My Database?

Making Do with Absent Foreign Keys

取自here.

添加具有现有子对象(数据库中存在的对象)的新实体时,如果子对象未被 EF 跟踪,则子对象将被重新插入。除非您先手动附加子对象。

尝试如下设置子对象状态:

public void InsertProduct(Product item)
{
    // Calling this code before the context is aware of the Child
    // objects will cause the context to attach the Child objects to the     
    // context and then set the state.
    // CustomerContext.Entry(childitem).State = EntityState.Unchanged
    CustomerContext.Entry(item.ChildObject).State = EntityState.Modified;

    CustomerContext.Entry(item).State = EntityState.Added;
    CustomerContext.Set<Product>().Add(item);
}