EF4 - 使用 lambda 表达式的 C# 排序

发布于 2024-10-20 20:26:07 字数 547 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

罗罗贝儿 2024-10-27 20:26:07

LINQ to Entities 中的语法可以类似于您的 SQL 查询:

var result = from a in context.master_table
             join b in context.detail_table on a.id equals b.a_id
             orderby a.id, b.order_field
             select new { /*...*/};

编辑:

根据您的评论的澄清 - 问题是在 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:

var result = from a in context.master_table
             join b in context.detail_table on a.id equals b.a_id
             orderby a.id, b.order_field
             select new { /*...*/};

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 the detail_table entries in this context, you have a grouping by master_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 the detail_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 using foo.detail_tables.OrderBy(x=>x.order_field).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文