我有一个实体框架模型,如下所示:
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 为“Sedan”的汽车的用户位于顶部。
在我的查询中,我通过包含属性“Cars”来进行一些急切的加载,但我不确定如何为子属性排序。
我正在使用基于此的通用存储库模式:http ://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work -patterns-in-an-asp-net-mvc-application
我的方法目前是这样的:
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();
}
}