保存时,Entity Framework Core是否不验证数据? [英] Entity Framework Core doesn't validate data when saving?

查看:121
本文介绍了保存时,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存储库中解释了该决定,如下:

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是否不验证数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆