【问题标题】:Linq Specified cast is not validLinq 指定的强制转换无效
【发布时间】:2014-01-09 18:54:24
【问题描述】:

我检查了很多有这个错误的帖子,但没有一个有这个特殊问题。 (另外我是 CSharp 的新手,一直是 Java 开发人员)

我遇到了一个例外

System.InvalidCastException 被捕获

在代码 sn-p 下方的 table2.Field("MEME_CK") 行上。

table2 中有大约 3K 行,我找不到避免错误转换行 table2.Field("MEME_CK")

的方法

数据可以为空、不存在、有效或无效。所以我尝试在泛型参数转换上使用可为空的运算符。还看到有可能表示不存在值的 DBNull 类。

有没有办法在进行“等于测试”或加入下面的代码之前预处理列数据? 即使在使用可空类型后如何避免强制转换?

以下代码基本上是基于 MemberID (即 MEME_CK 或 MemeCk)对两个数据表进行连接,并使用 CapHeadID、MemeCk 等作为字段创建新对象。

 var query =


       (from table1 in searchResult.AsEnumerable()
         join table2 in memberInfo.AsEnumerable()
         on table1.Field<decimal?>("MemeCk") equals
            table2.Field<decimal?>("MEME_CK") 
         select new
         {
              CapHeadID = table1.Field<decimal>("CapHeadID"),

             MemeCk = table1.Field<decimal>("MemeCk"),

             Suffix = table2.Field<decimal>("MEME_SFX"), 

             Suscriber = table2.Field<string>("SBSB_ID"),

              BusinessArea = table2.Field<string>("TEAM"),

             MemberName = table2.Field<string>("MemberName"),

             WorkTypeName = table1.Field<string>("WrkName"),

             SSN = table2.Field<string>("MEME_SSN"),

             AssignedUser = table1.Field<string>("AssignedUser") 

         }).Distinct().OrderBy(a => (a.Suscriber.IsNotNil() ? 

a.Suscriber : "")).Take(3000);  

【问题讨论】:

  • 如果您能解释这段代码的作用,将会很有帮助。这似乎是不必要的复杂。
  • 很抱歉。我已经为上面的代码添加了描述。
  • MEME_CK 的底层 SQL 类型是什么?
  • MEME_CK 基本上是 table1 中的 NUMBER(38,0) 和 table2 中的 Number

标签: c# sql linq


【解决方案1】:

您正在使用AsEnumerable 将查询从 IQueryable 转换为...基本上这意味着 LINQ 不会尝试为连接生成 SQL 代码,连接将在 C# 中完成。

考虑到这一点,您可以尝试将它们作为对象获取 - 像这样:

from table1 in searchResult.AsEnumerable()
     join table2 in memberInfo.AsEnumerable()
     on table1.Field<object>("MemeCk") equals
        table2.Field<object>("MEME_CK") 
     select new...

我不确定这是否会起作用,但它可能会起作用

【讨论】:

  • 感谢它确实通过了查询,但输出为“枚举未产生结果”
猜你喜欢
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
  • 1970-01-01
  • 2018-05-27
相关资源
最近更新 更多