我試圖更新Applicant
和ApplicantNotification
OneToOne關係表在數據庫中。但是,我正在嘗試不起作用。EF更新兩個實體不在數據庫中更新
我通過EF選擇對象然後覆蓋屬性,所以我會假設EF將跟蹤更改但不反映回數據庫。
問題: 如何更新EF中的兩個實體?
申請人:
[Index]
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ApplicantID { get; set; }
[Required]
public string ApplicantTitle { get; set; }
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string Address1 { get; set; }
[Required]
public string Address2 { get; set; }
[Required]
public string Address3 { get; set; }
[Required]
public string Postcode { get; set; }
[Required]
public string CaseReference { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
public ApplicantNotification Notification { get; set; }
ApplicantNotification:
[Index]
[Key, Column("ApplicantID"), ForeignKey("Applicant")]
public int ApplicantNotificationID { get; set; }
public bool FirstNotification { get; set; }
public bool SecondtNotification { get; set; }
public bool ThirdNotification { get; set; }
public bool FinalNotification { get; set; }
[DataType(DataType.Date)]
public DateTime? ReminderDate { get; set; }
public int ReminderFrequency { get; set; }
[DataType(DataType.Date)]
public DateTime? FirstNotificationDate { get; set; }
[DataType(DataType.Date)]
public DateTime? SecondNotificationDate { get; set; }
[DataType(DataType.Date)]
public DateTime? ThirdNotificationDate { get; set; }
public bool IsArchive { get; set; }
public virtual Applicant Applicant { get; set; }
方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ApplicantNotificationViewModel model)
{
if (ModelState.IsValid)
{
//select from ef
var applicant = (from a in db.Applicants
where a.ApplicantID == model.ApplicantID
select a).FirstOrDefault();
var applicantNotification = (from an in db.ApplicantNotifcations
where an.ApplicantNotificationID == model.ApplicantID
select an).FirstOrDefault();
SetApplicant(model, applicant);
SetApplicantNotification(model, applicantNotification);
using (var context = new WorkSmartContext())
{
try
{
db.Entry(applicant).State = EntityState.Modified;
db.Entry(applicantNotification).State = EntityState.Modified;
context.SaveChanges();
}
catch (Exception ex)
{
}
}
return RedirectToAction("Index");
}
return View(model);
}
感謝
不,我也試過,也不更新表 – Haris
爲什麼在這種情況下的交易?英孚已經將其包裝在一個。請參閱[這裏](https://msdn.microsoft.com/en-us/library/dn456843(v = vs.113).aspx) –
因爲我正在更新兩個實體?假設它會拋出第二個SaveChanges()的異常?這兩個表之間還存在OneToOne關係 – Haris