最佳情况(如果您需要元数据):
var rows = db.tblExample // database context
.OrderBy(x => x.SNo) // set an orderby
.AsEnumerable() // force query execution (now we have local dataset)
.Select(x => new
{
rowindex = i,
SNo = x.Sno,
Name = x.Name,
Age = x.Age
}); // now you have your original query
这里唯一的缺点是必须提取整个数据集才能获取此元数据。但是,如果您使用.Skip
&.Take
并且 LINQ 会自动将其转换为您的行号(您以后将无法使用该元数据)。例如
var pageIndex = /* ??? */;
var rows = db.tblExample
.OrderBy(x => x.SNo)
.Skip(pageIndex * 10).Take(10);
这应该给你类似的东西:
SELECT [t1].[SNo] AS [SNo],
[t1].[Name] AS [Name],
[t1].[Age] AS [Age]
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY [t0].[tblExample], [t0].[SNo]) AS [ROW_NUMBER],
[t0].[SNo],
[t0].[Name],
[t0].Age]
FROM [tblExample] AS [t0]
) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]
所以现在row_number
在 SQL 内部使用,但您无法在代码中访问它。
如果您真的想要这种访问,您最好手动将查询发送到服务器。一个可以很好地处理这种事情的库是dapper-dot-net,它看起来像:
class MyObject {
public Int32 rowindex;
public Int32 SNo;
public String Name;
publig Int32 Age;
}
/* build "connection" */
connection.Query<MyObject>("SELECT * FROM (SELECT ROW_NUMBER() ... ) ...");