EFCode First Property Null problem

放肆的年华 提交于 2019-11-30 16:14:23

问题


I use EFCode First in asp.net mvc 3 model. (Entity Framework 4.0 and EFCode First 0.8) The model is defined like below:

public class User
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int WorkedYears { get; set; }
}

when use db.Users.Find(1), will throw this error:

The 'WorkedYears' property on 'User' could not be set to a 'null' value. You must set this property to a non-null value of type 'Int32'.

Note: user.Id=1 exists in database, and WorkedYears of the record is NULL. if I set the WorkedYears = 0 in the database, the error will disappear, and also if I define the property like:public int? WorkedYears{get; set;}, the error will disapper too. but I don't want use int?, and also want the column keep NULL if not set. So is there any other solution to fix it?

Thanks a lot.


回答1:


Your model does not reflect your database and because of that it doesn't work. You must define WorkedYears with int?. If your view have this property mandatory you must define new class "view model" where WorkedYears will be null and handle what should that property contains if your database contains null.

Correct POCO for EF:

public class User
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int? WorkedYears { get; set; }
}

Correct view model:

public class UserModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int WorkedYears { get; set; }
}

Your controller is responsible for converting User <-> UserModel. If you still want to use single class you must add second not mapped property which will internally use nullabe WorkedYears:

public class User
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int? WorkedYears { get; set; }
    [NotMapped]
    public int WorkedYearsDisplay
    {
        get
        {
            return WorkedYears ?? 0;
        }
        set
        {
            WorkedYears = value == 0 ? new Nullable<int>() : value;
        }
    }
}

Conclusion: If your database contains nullable field which can contain null value you must have nullable property in your mapped class. No other way.



来源:https://stackoverflow.com/questions/5502872/efcode-first-property-null-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!