自定义Linq to Sql查询中的ExecuteScalar()模拟

Use*_*rol 3 .net sql sql-server linq-to-sql

我需要执行一个自定义的SQL查询,我不能用常规的L2S意味着:

select [row_number] from (select row_number() over (order by CreatedOn desc, ID desc) as [row_number], ID from MyTable) as T1 where ID = {0}
Run Code Online (Sandbox Code Playgroud)

所以我正在努力

var r = db.ExecuteQuery<int>(q, id).Single();
Run Code Online (Sandbox Code Playgroud)

但这不起作用(获取System.InvalidCastException:指定的强制转换无效).有什么建议?

Ale*_*lex 7

将您的代码更改为:

var r = db.ExecuteQuery<long>(q, id).Single();
Run Code Online (Sandbox Code Playgroud)

通过将返回类型从System.Int32(int)更改为System.Int64(long).

T-SQL函数ROW_NUMBER返回类型bigint不是int您所期望的.