EFCode First Property Null problem

孤街醉人 提交于 2019-11-30 16:04:34

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.

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