ASP.NET和EF Core-对于由Scaffold-DbContext生成的模型,ModelState.IsValid始终返回true [英] ASP.NET and EF Core - ModelState.IsValid always returns true for models generated by Scaffold-DbContext

查看:184
本文介绍了ASP.NET和EF Core-对于由Scaffold-DbContext生成的模型,ModelState.IsValid始终返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在ASP.NET Core控制器中验证由Scaffold-DbContext命令生成的模型.

所需/最大长度属性配置全部在EF核心生成的上下文类的onModelCreating方法中.

protected override void OnModelCreating( ModelBuilder modelBuilder ) {
    modelBuilder.Entity<ModelClass>( entity => {
        entity.ToTable( "ModelClass", "schema" );

        entity.Property( e => e.ModelClassCode )
              .IsRequired()
              .HasMaxLength( 30 );

我的控制器以JSON格式接收模型的数据,但是即使我发送无效数据,ModelState.IsValid始终返回true.

public IActionResult CreateModelClass( [FromBody]ModelClass modelClass ) {
    // ModelState.IsValid always returns true here

我将ModelState.IsValid设置为false的唯一方法是在模型类中添加数据注释.我想避免这种情况,因为运行scaffold命令会覆盖这些更改.

我在这里错过了什么吗?有人可以指出我的例子吗?我见过的与验证有关的都是使用数据注释.

解决方案

如@Smit的注释中所述,您可以使用Scaffold-DbContext命令中的-DataAnnotations开关来生成带有正确验证注释的模型.

在此处查看Scaffold-DbContext的文档: https://docs.microsoft.com/zh-CN/ef/core/miscellaneous/cli/powershell

I've been unable to validate models generated by the Scaffold-DbContext command in my ASP.NET Core controllers.

The required/max length property configurations are all in the onModelCreating method of the context class that EF core generated.

protected override void OnModelCreating( ModelBuilder modelBuilder ) {
    modelBuilder.Entity<ModelClass>( entity => {
        entity.ToTable( "ModelClass", "schema" );

        entity.Property( e => e.ModelClassCode )
              .IsRequired()
              .HasMaxLength( 30 );

My controller receives the data for the models as JSON but ModelState.IsValid always returns true even if I send invalid data.

public IActionResult CreateModelClass( [FromBody]ModelClass modelClass ) {
    // ModelState.IsValid always returns true here

The only way I've gotten ModelState.IsValid to be false is by adding data annotations to the model class. I'd like to avoid that because running the scaffold command will overwrite those changes.

Am I missing something here? Is there an example that someone can point me to? The ones I've seen related to validation are all using data annotations.

解决方案

As mentioned in @Smit's comment, you can use the -DataAnnotations switch in the Scaffold-DbContext command to generate the models with the correct validation annotations.

See the documentation for Scaffold-DbContext here: https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell

这篇关于ASP.NET和EF Core-对于由Scaffold-DbContext生成的模型,ModelState.IsValid始终返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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