2013-05-28 103 views
2

我有一個實體框架模型,看起來像:訂單在實體框架子集合

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用戶的「轎車」在頂部。

在我的查詢中,我通過包含屬性「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(); 
      } 
     } 

回答

2

的想法將是

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

(有點懷疑布爾,我認爲它應該是OrderByDescending,但是...我讓你檢查。)