2
我有一個實體框架模型,看起來像:訂單在實體框架子集合
public class User
{
public DateTime DateCreated {get;set;}
publc virtual List<Car> Cars {get;set;}
}
public class Car
{
public string ModelType {get;set;}
}
現在,我想所有的用戶,以便通過DESC,使得有汽車行駛的ModelType用戶的「轎車」在頂部。
在我的查詢中,我通過包含屬性「Cars」進行一些急切的加載,但我不確定如何通過子屬性進行排序。
我的方法是目前這樣的:
public List<User> GetUsers()
{
return Get(orderBy: o => o.OrderByDescending(u => u.DateCreated),
includeProperties: "Cars").ToList();
}
所以它有一個看起來像Get方法:
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}