【发布时间】:2016-11-17 20:22:47
【问题描述】:
好的,让我从我的模型开始:
联系方式类型:
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。但这应该是一对多的关系,我不想添加新的 ContactMethodType,只是为我的收件人分类一个新的联系方法。
我不确定这是什么时候发生的。也许我的模型不正确?根据选择的类型,我拉出该 Type 对象,并将其设置为 ContactMethod.Type 变量。但就像我说的那样,它不只是将它链接到现有的 ContactMethodType,而是尝试重新创建它,并且由于 GUID 已经存在,我收到无法创建记录的错误,因为密钥 (GUID) 已经存在。
有什么想法吗?
【问题讨论】:
-
您如何填充
myRecipient.ContactMethods?你能发布那个代码吗? -
我创建了一个 Contact Method 对象,填充它,然后:tmpRecipient.ContactMethods.Add(myCM);
-
您是否从查询中获取联系人方法列表的对象?或者,您是否将它们实例化为
new ContactMethod?后者将导致您报告的异常。 -
ContactMethod 来自这个:
public IActionResult AddContactMethod([Bind("Identifier,IsPreferred")]ContactMethod myCM, string Type, string CountryCode, string hidFirstName, string hidLastName, string hidCompany)ContactMethodType 我从一个 Linq 查询中得到:ContactMethodType tmpCMT = myCMTRepository.ContactMethodTypes.FirstOrDefault(x => x.ContactMethodTypeGUID == myCMTGuid);这个我拿那个对象和:myCM.Type = tmpCMT;
标签: c# mysql entity-framework asp.net-core