Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 466
Omar Avatar asked Nov 22 '09 04:11

Omar


2 Answers

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.

like image 95
Craig Stuntz Avatar answered Sep 25 '22 09:09

Craig Stuntz


I was having the same problem. I looked around and found a work around here. It describes the problem as being caused by the EF validation taking place before the Required field validation. It also shows how we can work around this problem by using a [DisplayFormat] Tag. Hope this will help you.

Here's the link to the question and the workaround:

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

like image 22
CodeNewa Avatar answered Sep 23 '22 09:09

CodeNewa