我有一个类似于以下的Entity Framework模型:
public class User
{
public DateTime DateCreated {get;set;}
publc virtual List<Car> Cars {get;set;}
}
public class Car
{
public string ModelType {get;set;}
}
现在我想获取所有用户,并按照降序排序,以便拥有“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();
}
}