问题
I have an ObjectQuery
like that:
ObjectQuery<Car> query = GetCarQuery();
than i want to order by property Date
on related entity Race
, somehting like
query = (ObjectQuery<Car>)query.OrderBy(x=> x.Races.Date);
query.Skip((page - 1) * rows).Take(rows).ToList();
was trying to go like that:
query = (ObjectQuery<Car>)query.OrderBy(i => i.Races.OrderBy(x=> x.Date));
query.Skip((page - 1) * rows).Take(rows).ToList(); //error here
and got an error when query executed
DbSortClause expressions must have a type that is order comparable.
Parameter name: key
Any ideas?
UPDATE:
After reading that http://blogs.msdn.com/b/alexj/archive/2009/02/25/tip-1-sorting-relationships-in-entity-framework.aspx i go like this:
var result = (from a in query
select new
{
Car= a,
Race= a.Races.OrderBy(x => x.Date)
}).Skip((page - 1) * rows).Take(rows).ToList();
Didn't get any errors but sorting seams to be not working.
One more try but with Entity SQL:
query = query.OrderBy("it.Races.Date");
query = query.Skip((page - 1) * rows).Take(rows).ToList();//error here
and getting error:
'Date' is not a member of 'Transient.collection[Race(Nullable=True,DefaultValue=)]'. To extract a property of a collection element, use a subquery to iterate over the collection. Near simple identifier, line 6, column 28.
So i think I've tried everything i could...
回答1:
And how do you expect it should work? You have cars and each of them can have many races so you cannot sort cars by race's data unless you do either:
- Sort cars with some aggregation of races - for example
.OrderBy(x=> x.Races.Max(Date))
- Flatten the result to have new record for each race (duplication of car)
For second solution you can try something like:
var result = (from car in query
from race in car.Races
select new
{
Car = car,
Race = race
})
.OrderBy(x => x.Race.Data)
.Skip((page - 1) * rows)
.Take(rows).ToList();
来源:https://stackoverflow.com/questions/6787760/entity-framework-objectquery-order-by-date-on-many-to-many-relation