马克·格雷夫(Marc Gravell)的Dynamic OrderBy在一种情况下有效,而在另一种情况下无效 [英] Marc Gravell's Dynamic OrderBy works in one case but not in other

查看:95
本文介绍了马克·格雷夫(Marc Gravell)的Dynamic OrderBy在一种情况下有效,而在另一种情况下无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Marc Gravell的代码对列进行动态排序.我要发布2个查询.它在一种情况下有效,但在第二种情况下无效.谁能告诉我我需要进行哪些更改才能使两个查询完美运行?

I am trying to do a dynamic order by on columns using Marc Gravell's code. I am posting the 2 queries. It works in one case but doesn't work in 2nd case. Can anybody tell me what changes I need to make to make both queries run perfectly?

这是马克·格雷夫(Marc Gravell)的答案的链接:

https://stackoverflow.com/a/233505

我正在使用Northwind数据库.这些都是我的查询:

I am using Northwind database. These are both my queries:

 var query = (from cust in northwindEntities.Customers
              select new 
              {
                  City = cust.City ,
                  Orders = northwindEntities.Orders
                       .Where(o => o.CustomerID == cust.CustomerID)
                       .OrderBy("OrderID")
              }); // doesn't work.

 var query = (from cust in northwindEntities.Customers
              select new 
              {
                  City = cust.City ,
                  //Orders = northwindEntities.Orders.Where(o => o.CustomerID == cust.CustomerID).
                  // OrderBy("OrderID")
              }).OrderBy("City"); // works

这里是第一个查询的例外:

Here is the exception of the 1st query:

LINQ to Entities无法识别该方法 'System.Linq.IOrderedQueryable 1[ConsoleApplication12.Order] OrderBy[Order](System.Linq.IQueryable 1 [ConsoleApplication12.Order], System.String)'方法,并且该方法无法转换为 存储表达式.

LINQ to Entities does not recognize the method 'System.Linq.IOrderedQueryable1[ConsoleApplication12.Order] OrderBy[Order](System.Linq.IQueryable1[ConsoleApplication12.Order], System.String)' method, and this method cannot be translated into a store expression.

推荐答案

很显然,由于与

var query = (from cust in northwindEntities.Customers
          select new 
          {
              City = cust.City ,
              Orders = northwindEntities.Orders
                   .MyCustomMethod()
          });

将不起作用. LINQ-to-Entities将遍历此表达式树,并尝试将其转换为SQL.它可以使用已知的方法子集转换为SQL.

will not work. LINQ-to-Entities will walk through this expression tree and try to convert it to SQL. It can work on known sub set of methods to translate to SQL.

但是在第二个查询中,自定义OrderBy方法动态创建了LINQ-to-Entities知道的OrderBy.

But in the second query, custom OrderBy method dynamically creates the OrderBy that LINQ-to-Entities knows.

这篇关于马克·格雷夫(Marc Gravell)的Dynamic OrderBy在一种情况下有效,而在另一种情况下无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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