在尝试使用实体框架检索数据并分配给我的自定义类Customer时,我不断收到以下错误消息
无法将源类型'system.nullable'转换为目标类型'int'
客户编号和路由具有Int32的数据类型,并且数据库中的字段允许空值
select new Customer()
{
AccountListId = j.cost1,
Csr = j.cost2,
CustomerName = j.cost3,
Address = j.cost4,
Telephone = j.cost5,
Contact = j.cost6,
CustomerNumber = j.cost7,
Branch = j.cost8,
Route = j.cost9,
}).ToList<Customer>();
我怎么处理这个?
显然,j.cost7
和j.cost9
属于Nullable<Int32>
类型。我假设,因为你没有告诉我们。
显然,你不能将Nullable<Int32>
分配给Int32
类型,因为,如果值为null
,你会怎么做?编译器不知道。您需要决定在这种情况下要做什么,并相应地编码。
假设您决定在数据库中使用-1
值时将null
指定为默认值,那么您可以使用null-coalescing operator并执行以下操作:
select new Customer()
{
AccountListId = j.cost1,
Csr = j.cost2,
CustomerName = j.cost3,
Address = j.cost4,
Telephone = j.cost5,
Contact = j.cost6,
CustomerNumber = j.cost7 ?? -1,
Branch = j.cost8,
Route = j.cost9 ?? -1,
}).ToList<Customer>();
如果你真正想要的是能够存储null
值(如果有的话),那么将CustomerNumber
和Route
的类型从Int32
更改为Nullable<Int32>
,或者使用替代语法:int?
。
尝试
if (j.cost7 == null)
{
CustomerNumber = 0;
}
else
{
CustomerNumber = j.cost7
}
您可以使用int的默认值。
例如:
CustomerNumber = j.cost7 ?? default(int),
Branch = j.cost8,
Route = j.cost9 ?? default(int),