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

标签 c# asp.net-core-mvc entity-framework-core

我有以下远程验证规则:

[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/

相关文章:

c# - 将 boost::archive 写入 C# 流

c# - 使用 LINQ,获取导航属性的前 x 行的方法是什么?

jquery - AJAX Post 到 ASP.NET MVC 6 Controller 操作方法和参数为 null

c# - 为现有 Entity Framework 实体创建基类型(EF 模型优先)

c# - 服务层分页,分页结果(逻辑放哪?)

c# - Unity 作为模拟环境——在执行大计算时延迟 Update() 循环

c# - 如何使用 MSAL 在控制台应用程序中代表用户获取访问 token 以调用 MS Graph?

asp.net-core-mvc - Core MVC - Ajax unobtrusive 不存在

azure - 在 ASP.NET Core Web 应用程序下的虚拟目录中运行面向 .net 4.6.1 的 MVC Web 应用程序。是否可以?

c# - 在ABP中从CrudAppService检索子实体