2016-11-17 64 views
0

好讓我開始與我的模型:實體框架代碼首先將記錄錯誤

聯繫方式類型:

public class ContactMethodType 
{ 
    [Key] 
    [HiddenInput(DisplayValue = false)] 
    public Guid ContactMethodTypeGUID { get; set; } 

    [Required(ErrorMessage = "Please enter a Contact Method Type Name.")] 
    public string Name { get; set; } 

    [Required(ErrorMessage = "Please enter a brief description.")] 
    public string Description { get; set; } 

    public bool IsActive { get; set; } 

    public virtual ICollection<ContactMethod> ContactMethods { get; set; } 

,聯繫方法:

public class ContactMethod 
{ 
    [Key] 
    [HiddenInput(DisplayValue = false)] 
    public Guid ContactMethodGUID { get; set; } 

    public virtual ContactMethodType Type { get; set; } 

    public string CountryCode { get; set; } 

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

    public bool IsPreferred { get; set; } 

} 

收件人:

public class Recipient 
{ 
    [Key] 
    public Guid RecipientGUID { get; set; } 

    [Required(ErrorMessage = "Please enter a Recipient's First Name.")] 
    public string FirstName { get; set; } 

    [Required(ErrorMessage = "Please enter a Recipient's Last Name.")] 
    public string LastName { get; set; } 

    public string Company { get; set; } 

    public UserGroup Owner { get; set; } 

    public List<ContactMethod> ContactMethods { get; set; } 

    public User CreatedBy { get; set; } 

    public DateTime CreatedOn { get; set; } 

    public User LastModifiedBy { get; set; } 

    public DateTime LastModifiedOn { get; set; } 

    public bool IsActive { get; set; } 

} 

我有兩個騙子圓通方法類型已經定義: 電子郵件和短信

現在我創建一個新的收件人,所以我添加所有需要的數據,以我的收件人對象,然後我打電話:

context.Recipients.Add(myRecipient); 
context.SaveChanges(); 

我能得到什麼是一個錯誤,我綁定添加一個新的ContactMethodType時已經存在。但是這應該是一對多關係,我不想添加新的ContactMethodType,只需爲我的收件人分類新的聯繫方式即可。

我不確定這是什麼時候發生的。也許我的模型不正確?根據選擇的類型,我將該類型對象拉出,並將其設置爲ContactMethod.Type變量。但正如我所說,而不是隻是將其鏈接到現有的ContactMethodType,它試圖重新創建它,並且由於GUID已經存在,所以我得到的錯誤是無法創建記錄,因爲密鑰(GUID)已經存在。

任何想法?

+0

你是如何填充'myRecipient.ContactMethods'?你可以發佈該代碼嗎? – wdosanjos

+0

我創建一個Contact Method對象,填充它,然後: tmpRecipient.ContactMethods.Add(myCM); – MarekT

+0

你是否從查詢中獲得聯繫方式列表的對象?或者,你是否將它們實例化爲「新的ContactMethod」?後者會導致您報告的異常。 – wdosanjos

回答

0

在與Marek討論這個離線事件之後,假設圖中所有添加的實體都是新的,它會被解析爲DbSet<TEntity>.Add(entity)

The API docs for Add ...

開始跟蹤給定的實體,而不是已經被跟蹤的任何其他實體到達,在加狀態,使得它們將被插入到數據庫時調用SaveChanges()叫做。

由於這款機型採用客戶端生成的密鑰,這意味着所有的實體都分配一個鍵值給他們的上下文之前,你不能使用任何的「聰明」的方法(如DbSet<TEntity>.Attach(entity))那會檢查關鍵值以確定每個實體是新的還是現有的。

添加新收件人後,可以在每個現有實體(即聯繫方式類型)上使用呼叫DbSet<TEntity>.Attach(entity)。或者,DbContext.Entry(entity).State = EntityState.Unchanged也會讓EF知道一個實體已經在數據庫中。

你也可以看看DbContext.ChangeTracker.TrackGraph(...),查看API docs瞭解更多信息。