我有以下远程验证规则:
[AcceptVerbs("Get", "Post")]
public IActionResult ValidateWindowEndDate(DateTime? endDate, DateTime? startDate)
{
int minWeeks = 8;
if (startDate.HasValue && endDate.HasValue
&& (endDate < startDate.Value.AddDays(minWeeks * 7)))
{
return Json(data: $"Inspection window end date must be at least {minWeeks} weeks after start date.");
}
return Json(data: true);
}
它链接到我的类中的一个属性,如下所示:
[Required]
[Remote("ValidateWindowEndDate", "InspectionWindow", AdditionalFields = "StartDate")]
public DateTime EndDate { get; set; }
当我在 View 中输入无效数据时,验证会按预期进行。但是,如果我在代码中获得该对象的实例,则将日期更改为无效日期并将其保存回数据库,例如
luInspectionWindow.EndDate = luInspectionWindow.StartDate.AddDays(1);
_context.Update(luInspectionWindow);
await _context.SaveChangesAsync();
然后保存无一异常(exception)地发生并且永远不会调用验证方法,这不是我期望的行为。我以为 EF 会拒绝记录无效?这是预期的行为吗?
最佳答案
因此,事实证明这是 EF 在 Core 中工作方式的改变。它现在根本不再进行验证,这由客户端和服务器(通过 Model.State
)决定。 Rowan Miller explains that decision in the EF repo如下:
In EF Core we dropped doing validation since it is usually already done client-side, server-side, and then in the database too.
我不能在我的特定场景中使用模型状态,所以我尝试通过 Validator
对象手动进行远程验证,但我没有任何运气任何一个。有关此问题的更多信息:Validator.TryValidateObject does not call Remote validation .
关于c# - Entity Framework Core 在保存时不验证数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43426175/