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

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)

我该如何处理?

sst*_*tan 5

显然,j.cost7j.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从更改Int32Nullable<Int32>,或使用替代语法:int?.