EF4 - 使用 lambda 表达式的 C# 排序
在 SQL 中我可以写
SELECT a.*, b.*
FROM master_table a
LEFT JOIN detail_table b ON (b.a_id = a.id)
ORDER BY a.id, b.order_field
Is it possible to do the same with EF4 ? 我无法理解如何指定 order by 子句。 到目前为止我尝试过
List<master_table> l = context.master_table.Include("detail_table").
OrderBy(x=>x.id).
ThenBy( //here is the problem, y=>y.detail_table.order_filed doesn't compile,
//y=>y.detail_tables.OrderBy(z=>z.order_field) - throws a run-time exception
).
ToList();
谢谢。
In SQL I can write
SELECT a.*, b.*
FROM master_table a
LEFT JOIN detail_table b ON (b.a_id = a.id)
ORDER BY a.id, b.order_field
Is it possible to do the same with EF4 ?
I cannot understand how to specify order by clause.
So far I tried
List<master_table> l = context.master_table.Include("detail_table").
OrderBy(x=>x.id).
ThenBy( //here is the problem, y=>y.detail_table.order_filed doesn't compile,
//y=>y.detail_tables.OrderBy(z=>z.order_field) - throws a run-time exception
).
ToList();
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
LINQ to Entities 中的语法可以类似于您的 SQL 查询:
编辑:
根据您的评论的澄清 - 问题是在 SQL 查询中您有要加入的成对项目(a、 b) - 在 Linq to Entities 查询中,您尝试通过导航属性进行二级排序。
不同之处在于,在此上下文中,
master_table
条目和detail_table
条目之间存在一对多关系,您可以按master_table
条目进行分组已经 - 考虑到能够在detail_table
级别表达排序顺序(对于编译器或一般情况)没有意义。当您枚举结果时,我会强制执行它 -
master_table
条目已经处于正确的顺序,只需使用foo.detail_tables.OrderBy(x=>x.order_field) 返回详细信息
。The syntax in LINQ to Entities can be similar to your SQL query:
Edit:
With the clarification from your comment - The problem is that in the SQL query you have pairs of items that you are joining (a,b) - while in the Linq to Entities query you are trying to do you want a secondary order by a navigation property.
The difference is that there's a one to many relationship between the
master_table
entries and thedetail_table
entries in this context, you have a grouping bymaster_table
entry already - given that it doesn't make sense (to the compiler or in general) to be able to express that sort order on thedetail_table
level.I would just enforce it when you enumerate the results - the
master_table
entries are already in the right order, just return the details usingfoo.detail_tables.OrderBy(x=>x.order_field)
.