Entity Framework Core doesn't validate data when saving?

∥☆過路亽.° 提交于 2019-12-01 04:32:32

问题


I have the following remote validation rule:

[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);
}

That's linked to a property in my class as follows:

[Required]
[Remote("ValidateWindowEndDate", "InspectionWindow", AdditionalFields = "StartDate")]
public DateTime EndDate { get; set; }

When I enter an invalid data in my view, the validation occurs as expected. But, if I get an instance of the object in code, then change the date to an invalid one and save it back to the database, e.g.

luInspectionWindow.EndDate = luInspectionWindow.StartDate.AddDays(1);
_context.Update(luInspectionWindow);
await _context.SaveChangesAsync();

then the save takes place without an exception and the validation method is never called, which wasn't the behaviour I was expecting. I thought EF would reject the record as invalid? Is this the expected behaviour?


回答1:


So, this turns out to be a change in the way EF works in Core. It now no longer does validation at all, that is left up to the Client and server (via Model.State). Rowan Miller explains that decision in the EF repo as follows:

In EF Core we dropped doing validation since it is usually already done client-side, server-side, and then in the database too.

I can't use the model state in my particular scenario, so instead I've tried to get Remote validation working manually via the Validator object, but I'm not having any luck with that either. More on that in this question: Validator.TryValidateObject does not call Remote validation.



来源:https://stackoverflow.com/questions/43426175/entity-framework-core-doesnt-validate-data-when-saving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!