Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 248
user7003875 Avatar asked Dec 12 '16 02:12

user7003875


1 Answers

As mentioned in @Smit's comment, you can use the --Data-Annotations 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

like image 128
user7003875 Avatar answered Dec 05 '22 09:12

user7003875