【发布时间】:2017-06-12 22:04:53
【问题描述】:
我正在尝试更新数据库中的Applicant 和ApplicantNotification OneToOne 关系表。但是,我正在尝试的方法不起作用。
我通过 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; }
申请人通知:
[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);
}
谢谢
【问题讨论】:
-
不,我也试过了,不会更新表格
-
为什么是这种场景下的事务? EF 已经将它包装成一个。见here
-
调用 SaveChanges() 一次。这就是使它成为交易的原因。阅读我的链接。
-
感谢您的尝试!!! :) @MatheusMiranda
-
将 context.SaveChanges() 更改为 db.SaveChanges()
标签: c# asp.net-mvc entity-framework asp.net-mvc-5