简体   繁体   English

实体框架:将分页与动态LINQ OrderBy结合

[英]Entity Framework: combining paging with Dynamic LINQ OrderBy

I am retriveing some data using Entity Framework like so: 我正在使用Entity Framework检索某些数据,如下所示:

var items = GetItems(storeNumber);

Sort(items);

Page(items);

return await items.ToListAsync();

I have these private helper methods: 我有以下私人助手方法:

private IQueryable<Item> GetItems(string storeNumber)
{
    return _dbContext.Items.Where(x => x.StoreNumber == storeNumber);
}

I sort the results using Dynamic LINQ. 我使用动态LINQ对结果进行排序。

private void Sort(IQueryable<Item> items, string fieldToSort, string sortDirection)
{
    items = items.OrderBy($"{fieldToSort} {sortDirection}");
}

In my Page method I get the exception 在我的Page方法中,我得到了异常

The method 'OrderBy' must be called before the method 'Skip' 必须在方法“跳过”之前调用方法“ OrderBy”

private void Page(IQueryable<Item> items, int skip, int take)
{
    items = items.Skip(skip).Take(take);
}

I had suspected that the reason for the error was because items needs to be IOrderedQueryable<Item> but there is no overload for the Dynamic LINQ OrderBy which returns IOrderedQueryable<T> . 我曾怀疑该错误的原因是因为项目需要为IOrderedQueryable<Item>对于动态LINQ OrderBy来说没有重载,该动态LINQ OrderBy返回 IOrderedQueryable<T> If I extract the Sort and Page code into the same method, using var it's no longer an issue, it infers the type. 如果我将Sort和Page代码提取到相同的方法中,则使用var不再是问题,它将推断类型。 The problem seems to be using the IQueryable interface when sorting and paging. 问题似乎是在排序和分页时使用IQueryable接口。 Is there a way I can break up this logic into separate methods but still use Dynamic LINQ for sorting? 有没有办法将这种逻辑分解为单独的方法,但仍使用Dynamic LINQ进行排序?

Any help is much appreciated. 任何帮助深表感谢。

You should return the newly constructed IQueryable from the Sort() and the Page() methods, just as you do for GetItems(). 您应该像对GetItems()一样,从Sort()和Page()方法返回新构造的IQueryable If you "rewrite" a parameter value inside a method like this, it has no effect on the value originally passed in to the parameter, because C# uses by-value parameter passing semantics 如果您在这样的方法中“重写”参数值,则它对最初传递给该参数的值没有影响,因为C#使用按值传递参数的语义

See this for more reference: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters 请参阅此以获取更多参考: https : //docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM