我使用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列表。当产品在DB中不存在时,我想添加它:
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);
}
答案 0 :(得分:1)
取自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);
}
答案 1 :(得分:-1)
如果向父类添加外键,则更容易:
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?