use*_*476 3 c# linq entity-framework-5
在尝试使用实体框架检索数据并分配给我的自定义类 Customer 时,我不断收到以下错误消息
无法将源类型“system.nullable”转换为目标类型“int”
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>();
Run Code Online (Sandbox Code Playgroud)
我该如何处理?
显然,j.cost7
和j.cost9
是 类型Nullable<Int32>
。我假设,因为你没有向我们展示。
显然,您不能将 a 分配Nullable<Int32>
给Int32
类型,因为如果值为 ,您会怎么做null
?编译器不知道。您需要决定在这种情况下要做什么,并相应地编码。
假设您决定将数据库-1
中的null
值分配为默认值,然后您可以使用空合并运算符并执行以下操作:
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>();
Run Code Online (Sandbox Code Playgroud)
如果您真正想要的是能够存储null
值(如果有),则将CustomerNumber
和的类型Route
从更改Int32
为Nullable<Int32>
,或使用替代语法:int?
.
归档时间: |
|
查看次数: |
4817 次 |
最近记录: |