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

asp.net-core-mvc entity-framework-core validation

Question

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
4
12/12/2016 2:31:07 AM

Accepted Answer

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

1
12/19/2016 6:22:59 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow