In MVC2 Entity Framework 4, server-side validation of a REQUIRED String Property does not function.

asp.net-mvc data-annotations entity-framework

Accepted Answer

I spent some time dealing with the same issue. I've found a little of information here: http://mvcmusicstore.codeplex.com/workitem/6604. Simply explained, Entity's Property Validation causes the exception "This field cannot be changed to a null value due to a System.Data.ConstraintException." to be raised. This validation, known as Validation Before Binding, takes place when your mvc application attempts to link the form field to the appropriate entity property (it happens when the form is submitted). The binder attempts to bind a null value to the property since the field is empty (and so converted to null), which violates the Non-Null constraint on the entity's property.

You will see the message from the "Required" annotation validation, which is carried out after the prebinding, if you post with a blank field (which is distinct from empty, hence null), since the property is no longer assigned to a null value. This message is Validation after PostBinding.

Using the annotation ConvertEmptyStringToNull = false; DisplayFormat;, which instructs the binder not to convert an empty string to null, is a workaround.

  [Required]
  [DisplayFormat(ConvertEmptyStringToNull = false)]
  public string YourStringProperty { get; set;}

Hope this is useful!

30
8/3/2012 8:36:47 PM

Popular Answer

This was quite useful. I'm using entity framework and MVC3. Even though I was directly giving my entities to the controller, I still received the same issue when the form was empty. Data validation is possible with entity framework by altering the automatically created code, however for me, establishing a distinct partial class of the entity worked better.

[MetadataType(typeof(TestEntityValidation))]
public partial class TestEntity{
}

public class TestEntityValidation{
    [Required]
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public String name { get;set}
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow