我在 asp.net mvc 3 模型中使用 EFCode First。 (实体框架 4.0 和 EFCode First 0.8)
该模型定义如下:
public class User
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int WorkedYears { get; set; }
}
使用时db.Users.Find(1)
,会抛出这个错误:
“User”的“WorkedYears”属性
无法设置为“空”值。
您必须将此属性设置为
“Int32”类型的非空值。
注意:数据库中存在user.Id=1,并且该记录的WorkedYears为NULL。
如果我在数据库中设置 WorkedYears = 0 ,错误就会消失,
另外,如果我将属性定义为:public int? WorkedYears{get; set;}
,错误也会消失。
但我不想使用 int?,并且还希望该列在未设置时保留 NULL。
那么还有其他解决方案可以解决吗?
多谢。
您的模型不反映您的数据库,因此它不起作用。您必须定义WorkedYears
with int?
。如果您的视图强制具有此属性,则必须定义新类“视图模型”,其中 WorkedYears 将为 null,并在数据库包含 null 时处理该属性应包含的内容。
正确的 EF 的 POCO:
public class User
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int? WorkedYears { get; set; }
}
正确的视图模型:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
public int WorkedYears { get; set; }
}
您的控制器负责转换User
UserModel
。如果您仍然想使用单个类,则必须添加第二个未映射的属性,该属性将在内部使用 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;
}
}
}
结论:如果您的数据库包含可为 null 的字段,并且该字段可以包含 null 值,则您的映射类中必须具有可为 null 的属性。别无退路。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)