Server-side validation of a REQUIRED String Property in MVC2 Entity Framework 4 does not work

前端 未结 3 1382
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 10:37

I\'m trying to get server-side validation of an Entity Framework String Property to work. Other server-side validation such as data type validation and required dateTime and

相关标签:
3条回答
  • 2020-12-14 11:05

    Sometimes in database first approach in EF, may you update your column from not null to can be null using SQL query and use 'Update Model From Database...' (in EDMX right click) then maybe property of that entity not updated properly and so if you have some null data in that column ,in mapping ,violation occurs and this error shown.

    To fix this; You can check the Nullable in Properties of that property of entity that you updated it.

    0 讨论(0)
  • i was having the same problem for a while. I have found a piece of explanation here: http://mvcmusicstore.codeplex.com/workitem/6604 . To put it in a nutshell, the exception "System.Data.ConstraintException: This property cannot be set to a null value" is thrown by Entity's Property Validation. This validation is performed when your mvc application tries to bind the form field to the corresponding entity property( it's called PreBinding Validation, and it occurs when submitting the form). As the field is empty( therefore convert to null), the binder tries to bind a null value to the property, which violates the Non-Null constraint on your entity's property.

    But if you post with a blank field ( that is different from empty, therefore null) Entity validation passes( as the property is not set to a null value anymore), and then your see the message from the "Required" annotation validation, that is performed after the prebinding (it's PostBinding Validation).

    A workaround is to use the annotation [DisplayFormat(ConvertEmptyStringToNull = false)] that tells to the binder not to convert an empty string to null.

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

    Hope, this helps!

    0 讨论(0)
  • 2020-12-14 11:23

    This was very helpful. I'm using MVC3 and entity framework. I was passing my entities directly into the controller, but got the same error when the form was blank. With entity framework you can do data validation by editing the auto-generated code, but creating a separate partial class of the entity worked better for me.

    [MetadataType(typeof(TestEntityValidation))]
    public partial class TestEntity{
    }
    
    public class TestEntityValidation{
        [Required]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        public String name { get;set}
    }
    
    0 讨论(0)
提交回复
热议问题