Linq-to-Entities动态排序 [英] Linq-to-Entities Dynamic sorting

查看:123
本文介绍了Linq-to-Entities动态排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的查询,如何使用字符串作为orderby参数?

  string sortColumn =Title; 

var items =(来自ctxModel.Items
中的ltem其中ltem.ItemID == vId
orderby //这里的东西
选择ltem).Skip(PageSize *的PageIndex)。取(每页);

更新:

我不能只是订单结果集,因为我 FIRST 需要排序,只有 到页面。

解决方案

其他人建议使用动态链接或其他库。 个人,我不会为这样一个小任务带来库依赖。但是您可以采取的另外两个路径是...




  • 使用对象调用语法并构建查询表达式动态树。例如...



请参阅 http://blog.cincura.net/229310-sorting-in-iqueryable-using-string-as-column-name/



重要的是考虑延期执行。您可以安全地构建返回一个 IQueryable 对象的查询,然后在该对象上运行对象查询排序。您的查询只能在数据实际访问时运行一次。



上面的博文是一个如何使用Expression API构建和表达树的示例您可以使用您的 OrderBy 。真的听起来很复杂MSDN文章可能是更好的参考。请参阅MSDN上的如何:使用表达式树构建动态查询。 / p>




  • 使用简单的路线使用整个查询的标题开关。



例如

  ItemType items = default(ItemType); 
switch(sortColumn)
{
caseTitle:
{
items = ctxModel.Items
.Where(i => i.ItemID == vId)
.OrderBy(i => i.Title);
}
break;
}


This is my query, how can I use string as orderby parameter?

string sortColumn="Title";

var  items = (from ltem in ctxModel.Items
              where ltem.ItemID == vId
              orderby //something here
              select ltem).Skip(PageSize * PageIndex).Take(PageSize);

UPDATE:
I can't just OrderBy the result set, because I FIRST need to sort, and only THEN to page.

解决方案

Others have suggested using Dynamic link or other libraries. Personally, I would not bring in a library dependency for such a small task. But two other paths that you can take are...

  • Use Object Call syntax and build your query expression tree dynamically. For example...

See http://blog.cincura.net/229310-sorting-in-iqueryable-using-string-as-column-name/

It is important to consider Deferred Execution in this scenario. You can safely build your query that returns an IQueryable object and then run a object query sort on that object. Your query will only be run once, when the data is actually accessed.

The above blog post is an example of how you can use the Expression API to build and expression tree that you can use for your OrderBy. It really just sounds complicated. The MSDN article may be a better reference. See How to: Use Expression Trees to Build Dynamic Queries on MSDN.

Or

  • Use the simple route and just use a switch on the title for the entire query.

Eg.

ItemType items = default(ItemType);
switch(sortColumn)
{
     case "Title":
     {
           items = ctxModel.Items
                    .Where(i => i.ItemID == vId)
                    .OrderBy( i => i.Title);
     }
     break;
 }

这篇关于Linq-to-Entities动态排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆