ASP.NET and EF Core - ModelState.IsValid always returns true for models generated by Scaffold-DbContext

偶尔善良 提交于 2019-12-12 12:25:01

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/41093419/asp-net-and-ef-core-modelstate-isvalid-always-returns-true-for-models-generate

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