3

我有一个实体框架模型,如下所示:

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();
            }
        }
4

1 回答 1

3

这个想法是

OrderByDescending(u => u.Cars.Any(c => c.ModelType == "Sedan"));

(对布尔值有一点怀疑,我认为应该是 OrderByDescending,但是......我让你检查一下。)

于 2013-05-28T21:16:24.847 回答