Entity Framework error when submitting empty field

2019-06-20 08:07发布

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.

8条回答
forever°为你锁心
2楼-- · 2019-06-20 09:00

Import the namespace:

using System.ComponentModel.DataAnnotations;

And add the attribute property [Required]

[Required]
public global::System.String MyProperty
    {
        get
        {
            return _MyProperty;
        }
        set
        {
            OnMyPropertyChanging(value);
            ReportPropertyChanging("MyProperty");
            _MyProperty = StructuralObject.SetValidValue(value, false);
            ReportPropertyChanged("MyProperty");
            OnMyPropertyChanged();
        }
    }

Thus ModelState.IsValid equals false, showing error message in the validation and will not fail on the server with Null.

查看更多
闹够了就滚
3楼-- · 2019-06-20 09:05

I set StoreGeneratedPattern property as Computed for each field and it solved the problem for me.

查看更多
登录 后发表回答