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 --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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With