【问题标题】:System.InvalidCastException: Specified cast is not valid (linq query)System.InvalidCastException:指定的强制转换无效(linq 查询)
【发布时间】:2016-10-06 03:54:06
【问题描述】:

Specified cast is not valid error at line: select new File.Models.FileDetail()。代码中的 DTTT 是一个数据表,FileDetial 是 Model 中的一个类,它具有 Filename、Dt、receivedcount、status 参数。我检查了所有字段数据类型,它们是正确的。不知道为什么我会收到这个错误。

return (from row in DTTT.AsEnumerable()
                        select new File.Models.FileDetail()
                         {
                             Filename = row.Field<string>("name"),
                             Dt = row.Field<DateTime?>("Dt"),
                             ReceivedCount = row.Field<int?>("count"),
                             status = row.Field<string>("status")

                         }

                    ).ToList();

【问题讨论】:

  • DtReceivedCount 是否可以为空?
  • 它们各自的 DbType 是什么 - Filename,Dt,receivedcount,status,其中一个不是您要进行类型转换的类型
  • 该方法的返回类型是什么?
  • 你应该添加你得到的异常细节
  • @MrinalKamboj 你说得对,我的 DT DBtype 是 char 并且在模型中我声明为 Datetime。现在可以了。

标签: c# linq


【解决方案1】:

您应该可以将其转换为 TimeSpan:

 Dt = row.Field<TimeSpan>("Dt");

Dt = (DateTime)(row.Field<DateTime>("Dt") == DBNull.Value ? DateTime.MinValue :row.Field<DateTime>("Dt"));

【讨论】:

    【解决方案2】:

    我的“DT”字段的 Dbtype 是 char,ReceivedCount 属性字段在我的模型中声明为 Datetime。所以有一个无效的强制转换异常。将我的模型字段数据类型更改为字符串有效。谢谢大家。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 2014-05-09
      • 2013-08-27
      • 1970-01-01
      相关资源
      最近更新 更多