我有一个 MeterPeak 实体,该实体有一个 MeterReading 实体作为外键(包含在问题的底部)。MeterReading 实体有一个由 MeterSiteId 和 DateTime 组成的复合主键。
所以我的理解是,在我的 MeterPeak 实体中,我必须输入与现有 MeterReading 实体匹配的 MeterSiteId 和 DateTime 以满足外键约束。我不应该被允许链接到不存在的外键。
但是,在 MeterPeakController 的编辑操作中,我有以下代码
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MeterPeak meterpeak)
{
if (ModelState.IsValid)
{
unitOfWork.MeterPeakRepository.Update(meterpeak);
unitOfWork.Save();
return RedirectToAction("Index");
}
ViewBag.MeterSiteId = new SelectList(unitOfWork.MeterSiteRepository.Get(b => true), "Id", "Location", meterpeak.MeterSiteId);
return View(meterpeak);
}
当我输入与现有仪表读数不匹配的 MeterSiteId 和 DateTime 并尝试保存时,我希望 ModelState.IsValid 检查返回 false,但事实并非如此。它只有在到达 unitOfWork.save() 行时才会失败,并且在保存对 dbcontext 的更改时会出错并出现此错误
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_dbo.MeterPeaks_dbo.MeterReadings_MeterSiteId_DateTime"
为什么 ModelState.IsValid 在进入 dbcontext.save 之前没有发现这个问题?
public class MeterPeak
{
[Key]
public int Id { get; set; }
[ForeignKey("PeakReading"), Column(Order = 1)]
public int MeterSiteId { get; set; }
[ForeignKey("PeakReading"), Column(Order = 2)]
public DateTime DateTime { get; set; }
public int? Rating { get; set; }
public String Note { get; set; }
public virtual MeterReading PeakReading { get; set; }
}
public class MeterReading
{
[Key, Column(Order = 1)]
[Required(ErrorMessage = "Please Select a Meter Site")]
public int MeterSiteId { get; set; }
[Key, Column(Order = 2)]
[Required]
public DateTime DateTime { get; set; }
//This is not the Primary key but I need one unique value to assist in getting records, especially from Javascript
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid SingleKey { get; set; }
public virtual MeterSite MeterSite { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:#,##0.00000#}", ApplyFormatInEditMode = true)]
public Double RawLevel { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:#,##0.00000#}", ApplyFormatInEditMode = true)]
public Double RawVelocity { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:#,##0.00000#}", ApplyFormatInEditMode = true)]
public Double RawFlow { get; set; }
[DisplayFormat(DataFormatString = "{0:#,##0.00000#}", ApplyFormatInEditMode = true)]
public Double ValidLevel { get; set; }
[DisplayFormat(DataFormatString = "{0:#,##0.00000#}", ApplyFormatInEditMode = true)]
public Double ValidVelocity { get; set; }
[DisplayFormat(DataFormatString = "{0:#,##0.00000#}", ApplyFormatInEditMode = true)]
public Double ValidFlow { get; set; }
[Range(-1, 3, ErrorMessage = "Rating must be one of the following -1,0,1,2,3")]
public int Rating { get; set; }
public bool? Valid { get; set; }
public virtual ICollection<Note> Notes { get; set; }
}