[英]Cannot convert source type system.nullable to target type int
I kept getting the error message below while trying to retrieve data using entity framework and assigning to my custom class Customer 在尝试使用实体框架检索数据并将其分配给自定义类Customer时,我一直收到以下错误消息
cannot convert source type 'system.nullable' to target type 'int' 无法将源类型“ system.nullable”转换为目标类型“ int”
CustomerNumber and Route have datatypes of Int32 and the fields in the database allows nulls CustomerNumber和Route的数据类型为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>();
How can I handle this? 我该如何处理?
Apparently, j.cost7
and j.cost9
are of type Nullable<Int32>
. 显然,
j.cost7
和j.cost9
的类型为Nullable<Int32>
。 I am assuming, because you haven't shown us. 我想是因为您没有给我们看。
Obviously, you can't assign a Nullable<Int32>
to an Int32
type, because, what do you do if the value is null
? 显然,您不能将
Nullable<Int32>
分配给Int32
类型,因为,如果该值为null
怎么办? The compiler doesn't know. 编译器不知道。 You need to decide what to do in that case, and code accordingly.
您需要确定在那种情况下该做什么,并相应地进行编码。
Let's say you decide to assign -1
as a default value in case of a null
value in the database, then you can use the null-coalescing operator and do something like this: 假设您决定在数据库中值为
null
情况下将-1
分配为默认值,然后可以使用空值合并运算符并执行以下操作:
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>();
If, what you really want, is to be able to store the null
value if there is one, then change the type of CustomerNumber
and Route
from Int32
to Nullable<Int32>
, or using an alternate syntax: int?
如果您真正想要的是能够存储
null
值(如果存在),则将CustomerNumber
的类型和Route
从Int32
更改为Nullable<Int32>
,或使用其他语法: int?
. 。
Try 尝试
if (j.cost7 == null)
{
CustomerNumber = 0;
}
else
{
CustomerNumber = j.cost7
}
You can use the default value of an int. 您可以使用int的默认值。
Eg: 例如:
CustomerNumber = j.cost7 ?? default(int),
Branch = j.cost8,
Route = j.cost9 ?? default(int),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.