Entity Framework Core 在保存时不验证数据?

Entity Framework Core doesn#39;t validate data when saving?(Entity Framework Core 在保存时不验证数据?)

本文介绍了Entity Framework Core 在保存时不验证数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下远程验证规则:

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();

然后保存不会发生异常,并且永远不会调用验证方法,这不是我所期望的行为.我以为 EF 会拒绝记录无效?这是预期的行为吗?

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?

推荐答案

因此,事实证明这是 EF 在 Core 中工作方式的改变.它现在根本不再进行验证,这留给客户端和服务器(通过 Model.State).Rowan Miller 在 EF repo 中解释了这一决定,如下:

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:

在 EF Core 中,我们放弃了验证,因为它通常已经在客户端、服务器端完成,然后在数据库中完成.

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 不调用远程验证.

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.

这篇关于Entity Framework Core 在保存时不验证数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Entity Framework Core 在保存时不验证数据?

基础教程推荐