ConstraintException thrown when posting empty data for non-nullable properties
I am currently working with model validation, using an EF4 entity model, DataAnnotations and partial classes with MetadataType connections.
In my model, I have an Employee entity for which some of properties are non-nullable. I have also created a partial class and a meta data class for model validation, as is described in this blog post.
This works great. The Employee class is validated properly, with minimum effort. My entities are validated with standard validation attributes as well as custom ones. Lovely.
However, the application crashes when I post empty text input elements in my Create/Edit views. A ConstraintException is thrown before my view controller actions are executed, which means that I cannot act on the constraint exception within my action.
The exception is caused by the fact that empty posted data will cause the corresponding model properties to be set to null, which conflicts with the non-nullable properties in the entity model.
However, since I have custom model validation classes in which I add Required attributes to mandatory properties, I do not need the non-nullable attributes in my entity model. As such, I set the nullable property to (None)…and the ConstraintException is history!