【问题标题】:"Specified cast is not valid" error in LINQ's orderby clauseLINQ 的 orderby 子句中的“指定转换无效”错误
【发布时间】:2012-06-04 17:56:18
【问题描述】:

我正在 LINQ 中的两个数据表之间进行右连接。我在 orderby 行 ""Specified cast is not valid" 收到错误。

“SomeOtherID”列是 dbml 中的 System.Int64 类型,并允许 DBNull。该列在数据中有一些空值,这是有效的。似乎必须在 orderby 语句中以某种方式处理这些空值,但我不确定如何处理。数据通过网络服务进入。我检查了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
                                     {
                                         ......
                                     });

【问题讨论】:

  • 解决方案适合你吗???
  • 重新标记 - 我认为这是 LINQ to SQL 而不是 LINQ to Entities。无论哪种方式,它都不在内存 LINQ 中。
  • 回滚,这不是 LINQ to SQL 或 LINQ to Entities。这是 LINQ to DataTables。
  • @Danny 我使用了包含任何类型 linq 的通用 linq 标签。我不明白你想做什么!数据表在内存中。
  • @Tony_Henrich 我的错误,从原始标签(c#linq)中看不清楚。

标签: c# .net linq datatable nullable


【解决方案1】:

同时检查:LINQ: OrderBy with nullable columns in TypedDataSets

试试下面的方法

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
       {
           ......
       });

【讨论】:

    猜你喜欢
    • 2015-05-28
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    相关资源
    最近更新 更多