问题
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