开发者

EF4 - C# Sorting using lambda expression

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 i开发者_开发百科s 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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜