我正在使用以下代码从 Web 表单中收集数据:
secondContact.FirstName = txtFirstNameContact2.Text;
secondContact.LastName = txtlastNameContact2.Text;
secondContact.EmailAddress = txtEmailAddressContact2.Text;
secondContact.PhoneNumber = txtPhone1Contact2.Text + txtPhone2Contact2.Text + txtPhone3Contact2.Text;
if (!string.IsNullOrEmpty(rblContactTypeContact2.SelectedValue))
{
secondContact.SecondaryContactTypeID = Convert.ToInt32(rblContactTypeContact2.SelectedValue);
}
secondContact.ContactPosition = 2;
secondContact.ProspectID = prospect.Id;
将代码发送到存储库以使用以下代码保存(它成功获取了前景.Id):
if (prospect.Id != 0)
{
if (!string.IsNullOrEmpty(secondContact.FirstName) || !string.IsNullOrEmpty(secondContact.LastName) || !string.IsNullOrEmpty(secondContact.EmailAddress) || !string.IsNullOrEmpty(secondContact.PhoneNumber))
{
this.repository.SaveAltContact(prospect.Id, 2, secondContact);
}
}
存储库尝试保存数据:
public void SaveAltContact(int prospectID, int contactPosition, SecondaryContact contact)
{
using (var context = new CoyleHomeBuyerEntities())
{
SecondaryContact currentAltContact = new Model.SecondaryContact();
currentAltContact = (from sec in context.SecondaryContact
where sec.ContactPosition == contactPosition
where sec.ProspectID == prospectID
select sec).FirstOrDefault();
if (currentAltContact == null)
{
context.AddToSecondaryContact(currentAltContact);
}
currentAltContact.FirstName = contact.FirstName;
currentAltContact.LastName = contact.LastName;
currentAltContact.EmailAddress = contact.EmailAddress;
currentAltContact.PhoneNumber = contact.PhoneNumber;
currentAltContact.SecondaryContactTypeID = contact.SecondaryContactTypeID;
currentAltContact.ProspectID = prospectID;
currentAltContact.ContactPosition = contactPosition;
context.SaveChanges();
}
}
在此行之后它总是失败并出现 Null 异常:
context.AddToSecondaryContact(currentAltContact);
我很困惑,因为我希望上面的查询此时返回一个 NULL 值。 SecondaryContactID
设置为主键并自动递增。
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: entity
有人可以指出我在尝试向数据库添加新行时为什么失败的正确方向吗?