14

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 numeric EF properties are working.

This in VS 2010, .Net 4.0, MVC2 + Cloud, ADO.Net Entity Framework.

The String Property I am having issues with is mapped to a SQL 2008, Varchar(50) non-nullable column.

When I try to post to my Create action with an empty string for this Property, I get the follwing error.

Exception Details: System.Data.ConstraintException: This property cannot be set to a null value.

When I post to the action with a blank space, I successfully get a required field validation message.

I have tried using Data Annotations and ClientSideValidation but there seems to be issues with ClientSideValidation working on partial views and jquery dialogs.

Here is the orginal autogenerated code from the entity framework.

[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String GradeTypeName
{
    get
    {
        return GradeTypeName;
    }
    set
    {
        OnGradeTypeNameChanging(value);
        ReportPropertyChanging("GradeTypeName");
        _GradeTypeName = StructuralObject.SetValidValue(value, false);
        ReportPropertyChanged("GradeTypeName");
        OnGradeTypeNameChanged();
    }
}

Depending on the signature of the Action method (CREATE or EDIT), the exception can occur before stepping into the method or within the method when UpdateModel() is called. The inner exception is at the line below from the model.designer.cs file.

_GradeTypeName = StructuralObject.SetValidValue(value, false);

I have been able to reproduce this on a simple mvc2 web application.

tereško
  • 58,060
  • 25
  • 98
  • 150
HackITMngr
  • 263
  • 3
  • 11

3 Answers3

30

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!

tinesoft
  • 766
  • 8
  • 13
  • Thanks! This was a problem for me until I found your post. – jrob Sep 29 '10 at 06:57
  • No, problemo! I'm Glad this has helped! – tinesoft Oct 03 '10 at 07:25
  • 1
    Solved a problem I've been banging my head against the wall over for weeks. – Major Productions Jan 18 '11 at 20:38
  • Is there a way to set this globally instead of tagging each property? – AndyMcKenna Nov 02 '11 at 15:37
  • 2
    When the framework attempts to auto-create the schema, the column will still be set up to allow nulls. If you want the column to generate as a non-nullable column, change the required attribute to `[Required(AllowEmptyStrings=true)]`. – Mark Hildreth Oct 15 '13 at 20:22
  • I don't know whether my comment deserve a question itself... What's happening to me is this: I have an EF Entity generated from oracle DB, I'm saving data to it by assigning fields, e.g. myrecord.myfield=" ", so BLANK SPACE, not empty, then db.Entity.Add(myrecord) will fail, Validation errors, myfield can not be NULL. Something is keep trying to put NULL instead of a blank. If I manually UPDATE with SQL then no problems. I tried to put ConvertEmptyStringToNull=false on the generated Entity (even if I'm NOT storing empty string but blank) but I've got the same error. Any ideas? – tonjo Jul 21 '16 at 08:59
4

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}
}
James
  • 194
  • 3
  • 10
2

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.

Majid
  • 13,853
  • 15
  • 77
  • 113