asp.net-mvc-2.net-4.0.net-4.0-beta-2

Entity Framework error when submitting empty fields


VS 2010 Beta 2, .NET 4.

In my ASP.NET MVC 2 application, when I submit a form to an action method that accepts an object created by the entity framework, I get the following error:

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

Source Error: 


Line 4500:                OnTextChanging(value);
Line 4501:                ReportPropertyChanging("Text");
Line 4502:                _Text = StructuralObject.SetValidValue(value, false);
Line 4503:                ReportPropertyChanged("Text");
Line 4504:                OnTextChanged();

The property is called "Text" and is of type "text NOT NULL" in MS SQL 2008.

My action will check if the value is nullorempty, if it is, a model error will be added, but I get the error as soon as I submit the form.


Solution

  • Are you binding directly to the entity? Sure looks like it. So you have two choices:

    1. Write a custom model binder which translates null -> empty string.
    2. Bind to an edit model which allows nulls instead, and then change this to empty string when you copy the values to the entity in the action.

    I'd choose #2, personally. I think you should always use view/edit models, and this is a great example of why.