Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Database First Automatically Validate Max Length for Properties

I'm using EF Database First with an existing legacy database. Almost every field has a maxlength value in the database, and I can view this value in the .edmx file.

For example, on of the fields CCSTATUS is nvarchar(20). When the user inputs more than 20 chars, it clears ModelState.IsValid, but throws an DbEntityValidationException on db.SaveChanges().

For properties that I've added DataAnnotations to, when they fail to validate, they add model errors, which can then be displayed to the user so they can be corrected. I'm aware that I could add [MaxLength(n)] attributes to all of the properties in the Model MetaData classes, but is there a way to have EF add Model Errors instead of throwing DbEntityValidationException when a value is greater than the maxlength for the property?

EDIT

Thanks for the answers everyone. I ended up using EF Power Tools Reverse Engineer Code First feature to generate Code First models from my database, which included the appropriate maxlength attributes and other necessary annotations.

like image 936
nb_ Avatar asked Sep 10 '26 13:09

nb_


1 Answers

The reason of this behavior is that EF and ASP.NET MVC are two different things. The ModelState is a concept of MVC and it has nothing to do with EF edmx metadata. If you want to use the same class to represent action input and a domain entity then you should go with the [MaxLength(n)] attribute solution. However, I would recommend to use a viewmodel/dto instead.

I wouldn't go with the solution of @Reinard (catching the DbEntityValidationException) for the following reasons: you are validating input and you are checking the result of the input validation inside the controller action. DbEntityValidationException indicates a problem at a completely different layer (database). This kind of layer mixing will hurt you sooner or later. Another reason is that you shouldn't use exceptions like this, but this is a different topic, e.g.: Why not use exceptions as regular flow of control?

like image 121
Peter Porfy Avatar answered Sep 13 '26 03:09

Peter Porfy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!