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

标签 c# entity-framework orm

我使用代码优先的 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);
    }

最佳答案

取自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);
}

关于c# - 插入新实体而不创建子实体(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28809036/

相关文章:

c# - 在附加到发布版本时,是否有任何工具可以用来调试信息?

c# - 如何以编程方式转换以下 xaml?

javascript - Sequelize : Check and add BelongsToMany (N to N) relation

c# - 使用 JQuery 获取列表框中的所有列表项?

c# - 在 EF4.1 中正确地从上下文附加和分离实体

c# - 最小起订量单元测试 - 值不能为空

.net - Entity Framework 支持的数据库

ruby-on-rails - 如何分组并获取 has_many :through rails 中的计数

entity-framework - 在 EF 4.1 中使用 DbContext 和数据库优先

c# - 单元测试事件触发的行为