问题描述
我正在尝试使用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:
推荐答案
很显然,由于与
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在一种情况下有效,而在另一种情况下无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!