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

问题描述 投票:0回答:3

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

我怎么处理这个?

c# linq entity-framework-5
3个回答
2
投票

显然,j.cost7j.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值(如果有的话),那么将CustomerNumberRoute的类型从Int32更改为Nullable<Int32>,或者使用替代语法:int?


0
投票

尝试

if (j.cost7 == null)
{
    CustomerNumber = 0;
}
else
{
    CustomerNumber = j.cost7
}

0
投票

您可以使用int的默认值。

例如:

CustomerNumber = j.cost7 ?? default(int),
        Branch = j.cost8,
        Route = j.cost9 ?? default(int),
© www.soinside.com 2019 - 2024. All rights reserved.