【问题标题】:Cannot convert source type system.nullable to target type int无法将源类型 system.nullable 转换为目标类型 int
【发布时间】:2015-09-21 19:20:28
【问题描述】:

尝试使用实体框架检索数据时,我不断收到以下错误消息 并分配给我的自定义类 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>();

我该如何处理?

【问题讨论】:

  • 如果数据库中的值为null,您想为Int32 字段分配什么。显然,null 无效。你想设置0还是-1,还是什么?

标签: c# linq entity-framework-5


【解决方案1】:

试试

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

【讨论】:

  • 从语法上讲,在 with 构造函数中这是行不通的。
【解决方案2】:

显然,j.cost7j.cost9 的类型是 Nullable&lt;Int32&gt;。我假设,因为您没有向我们展示。

显然,您不能将Nullable&lt;Int32&gt; 分配给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&lt;Int32&gt;,或使用替代语法:int?

【讨论】:

  • 如果我知道 j.cost7 永远不会为空怎么办?比如说,为了验证的目的,我已将其设置为可为空,并且我知道 asp net core 将拒绝所有 j.cost7 为空的模型。为什么在这种情况下 null 宽恕运算符不起作用?例如。 CustomerNumber = j.cost7!,
【解决方案3】:

您可以使用 int 的默认值。

例如:

CustomerNumber = j.cost7 ?? default(int),
        Branch = j.cost8,
        Route = j.cost9 ?? default(int),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多