在实体框架中按子集合排序

时间:2013-05-28 21:13:38

标签: c# entity-framework entity-framework-4

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

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

1 个答案:

答案 0 :(得分:2)

这个想法将是

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

(毫无疑问,布尔值,我认为它应该是OrderByDescending,但是......我让你检查一下。)