efcore: OrderBy and ThenBy problem
I know that this came from EF6, but it is ugly construction. It is very difficult to do chain of method with conditions:
var items = db.Items;
if (condition1)
{
items = items.OrderBy(x => x.Field1);
}
if (condition2)
{
items = items.ThenBy(x => x.Field2);
}
if condition1
is false, then ThenBy throw exception. There are no really need to call OrderBy
first and ThenBy
next. More convinient would be method AddOrderBy
instead of that two. Or in addition for them.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 16 (4 by maintainers)
@anpete @MichaelKetting reading the whole thread I tend agree that the fact that queries returned from all operators are
IOrderedQueryable<T>
is less than ideal. Any thoughts on this?I tried it and this is not work.
DbQuery<T>
realize bothIQuerable<T>
andIOrderedQuerable<T>
. There are no way to realize was OrderBy called or not.Magic of OrderBy -> ThenBy work on interfaces that they return and extend (as extensition method). It work only if you call them in one chain
var items = db.Items.OrderBy(x => x.Time).ThenBy(x => x.Name)
and broke in this scenario:
I see what you’re saying. You can do that yourself:
In general it doesn’t make a terrible amount of sense to do an
AddOrderBy
(meaningThenBy
) without explicitly tracking which ordering it’s coming after, since the two sorts can’t be done independently. (I’m not even sure how you gotdb.Items.ThenBy
to compile.)This is more of a corefx question.