好讓我開始與我的模型:實體框架代碼首先將記錄錯誤
聯繫方式類型:
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)已經存在。
任何想法?
你是如何填充'myRecipient.ContactMethods'?你可以發佈該代碼嗎? – wdosanjos
我創建一個Contact Method對象,填充它,然後: tmpRecipient.ContactMethods.Add(myCM); – MarekT
你是否從查詢中獲得聯繫方式列表的對象?或者,你是否將它們實例化爲「新的ContactMethod」?後者會導致您報告的異常。 – wdosanjos