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.