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

Jan*_*oem 5 c# orm entity-framework

我使用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; }
}
Run Code Online (Sandbox Code Playgroud)

我收到了客户ID以及产品ID列表.当产品在DB中不存在时,我想添加它:

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

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

这是插入方法:

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

Pau*_*hra 3

取自这里。

添加具有现有子对象(数据库中存在的对象)的新实体时,如果 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);
}
Run Code Online (Sandbox Code Playgroud)