且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

"指定的转换是无效"在LINQ的排序依据子句中的错误

更新时间:2023-02-17 12:20:29

另外,请检查:的 LINQ:排序依据与TypedDataSets 空列

试试下面的方法

  VAR的查询=
(从表1中DataTable1.AsEnumerable()
  加入表2中DataTable2.AsEnumerable()
  在(INT)表1 [客户ID]等于(INT)表2 [客户ID]
   成outer.DefaultIfEmpty从表2的外()
// order by子句此处更改
 排序依据
   (Convert.IsDBNull(表2 [SomeOtherID])0:(INT)?
                          Convert.ToInt32(表2 [SomeOtherID]))
    选择新
       {
           ......
       });
 

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

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