“Specified cast is not valid” error in LINQ's orderby clause

流过昼夜 提交于 2019-12-24 02:34:02

问题


I am doing a right join between two datatables in LINQ. I am getting an error at the orderby line ""Specified cast is not valid".

"SomeOtherID" column is of type System.Int64 in the dbml and allows DBNull. The column has some null values in the data, which is valid. It seems these nulls have to be handled in a certain way in the orderby statement but I am not sure how. The data is coming in through a web service. I checked the reference.cs file and the corresponding property for the column is an int.

How should the LINQ statement be?

 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:


Also check : LINQ: OrderBy with nullable columns in TypedDataSets

try below way

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


来源:https://stackoverflow.com/questions/10885837/specified-cast-is-not-valid-error-in-linqs-orderby-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!