2015-03-02 25 views
5

我使用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); 
    } 

回答

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); 
} 
相關問題