【问题标题】:Order by child collection in entity framework在实体框架中按子集合排序
【发布时间】:2013-05-28 21:13:37
【问题描述】:

我有一个看起来像这样的实体框架模型:

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

【问题讨论】:

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


    【解决方案1】:

    这个想法是

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

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

    【讨论】:

      猜你喜欢
      • 2012-04-13
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      相关资源
      最近更新 更多