开发者

EFCode First Property Null problem

开发者 https://www.devze.com 2023-02-21 07:12 出处:网络
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:

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:

开发者_StackOverflow

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号