繁体   English   中英

无法将源类型system.nullable转换为目标类型int

[英]Cannot convert source type system.nullable to target type int

在尝试使用实体框架检索数据并将其分配给自定义类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>();

我该如何处理?

显然, j.cost7j.cost9的类型为Nullable<Int32> 我想是因为您没有给我们看。

显然,您不能将Nullable<Int32>分配给Int32类型,因为,如果该值为null怎么办? 编译器不知道。 您需要确定在那种情况下该做什么,并相应地进行编码。

假设您决定在数据库中值为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>();

如果您真正想要的是能够存储null值(如果存在),则将CustomerNumber的类型和RouteInt32更改为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),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM