0

嗨,我最近学习了实体框架和 linq,我被要求转换这个存储过程:

CREATE PROCEDURE [dbo].[GetBooks]
@numberOfBooksOnPage int,
@pageNumber int
    AS
    BEGIN

    WITH AllBooks AS
    (
        SELECT ROW_NUMBER() OVER(ORDER BY Id) AS RowId,
        Id , Name , Author , Description , PublicationDate , CategoryId
        FROM Books
    )

    SELECT Id , Name , Author , Description , PublicationDate , CategoryId
    FROM AllBooks
    WHERE RowId BETWEEN ((@pageNumber - 1) * @numberOfBooksOnPage) + 1 AND @pageNumber * @numberOfBooksOnPage
    ORDER BY RowID
    END

到目前为止,我只设法获得每页显示的书籍总数,但我仍然需要找到一种通过 pageNumber 获取书籍的方法。

这是我到目前为止所拥有的:

var books = bookContext.Books.Take(numberOfBooksOnPage);

那么如何在我的 linq 查询中表示存储过程中写入的内容呢?

4

5 回答 5

3

如果你想做一个简单的分页,这里有一个快速的解决方案:

var books = bookContext.Books.OrderBy(x => x.Id).Skip(pageNo*booksPerPage).Take(booksPerPage);
于 2013-03-05T13:43:53.337 回答
1

将 Skip() 方法与 take 结合使用

var books = bookContext.Books.OrderBy(b => b.Id).Skip(pageNumber * numberOfBooksOnPage).Take(numberOfBooksOnPage)
于 2013-03-05T13:43:40.473 回答
1

你想跳过-

var books = bookContext.Books.OrderBy(b => b.someField).Skip(pageNumber * numberOfBooksOnPage).Take(numberOfBooksOnPage);
于 2013-03-05T13:44:01.010 回答
1

LINQ 中的分页通常涉及使用SkipTake扩展,因此:

var numOfBooksPerPage = 20;
var currPage = 3;

var books = bookContext.Books.Skip(currPage * numOfBooksPerPage).Take(numOfBooksPerPage);
于 2013-03-05T13:44:37.543 回答
1

如前所述,如果您想对结果进行分页,最好将TakeSkip结合使用,就像前面的答案一样。Linq to sql 没有公开Between方法,这可以很容易地用Where子句替换。或者,您可以编写自己的扩展方法:

public static IEnumerable<TSource> Between<TSource, TResult>
(
    this IEnumerable<TSource> source, Func<TSource, TResult> selector,
    TResult lowest, TResult highest
)
    where TResult : IComparable<TResult>
{
    return source.OrderBy(selector).
        SkipWhile(s => selector.Invoke(s).CompareTo(lowest) < 0).
        TakeWhile(s => selector.Invoke(s).CompareTo(highest) <= 0 );
}

试一试:

public class Book
{
    public string Name { get; set; }
    public int Pages { get; set; }
}    

[Test]
public void TestBooks()
{
    var listOfNumbers = new List<Book>() {new Book(){Pages = 10}, new Book(){Pages = 44}};
    var result = listOfNumbers.Between(x => x.Pages, 0, 29);
}
于 2013-03-05T14:01:05.453 回答