LINQ的orderby子句中出现“指定的类型转换无效”错误

3
我正在使用LINQ在两个数据表之间执行右连接。在orderby语句处出现了错误“指定的强制转换无效”。
数据库中“SomeOtherID”列的类型为System.Int64,允许DBNull。该列在数据中有一些空值,这是有效的。似乎这些空值必须以某种方式在orderby语句中处理,但我不确定如何处理。数据通过Web服务传输。我检查了reference.cs文件,该列的相应属性为int。
LINQ语句应该怎么写呢?
 var query = (from table1 in DataTable1.AsEnumerable()
                          join table2 in DataTable2.AsEnumerable()
                              on (int) table1["CustomerID"] equals (int) table2["CustomerID"] into outer
                          from table2 in outer.DefaultIfEmpty()
                          orderby (int?)table2["SomeOtherID"] 
                          select new
                                     {
                                         ......
                                     });

1
这个解决方案对你有用吗? - Pranay Rana
重新标记 - 我假设这是 LINQ to SQL 而不是 LINQ to Entities。无论哪种方式,它都不是内存中的 LINQ。 - Danny Varod
回滚,这不是LINQ to SQL或LINQ to Entities。这是LINQ to DataTables。 - jrummell
@Danny 我使用了泛型linq标签,它包括任何类型的linq。我不明白你试图做什么!这些数据表在内存中。 - Tony_Henrich
@Tony_Henrich 对不起,从原始标签([tag:c#]和[tag:linq])中并不清楚。 - Danny Varod
1个回答

3

还可以尝试以下方法:LINQ:在TypedDataSets中使用可空列进行OrderBy

尝试以下方式:

var query = 
(from table1 in DataTable1.AsEnumerable()
  join table2 in DataTable2.AsEnumerable()
  on (int) table1["CustomerID"] equals (int) table2["CustomerID"] 
   into outer from table2 in outer.DefaultIfEmpty()
//order by clause changed here     
 orderby 
   (Convert.IsDBNull(table2["SomeOtherID"]) ? 0 : (int?)
                          Convert.ToInt32(table2["SomeOtherID"]))
    select new
       {
           ......
       });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接