2015-04-22 47 views
0

我有這樣的模式:使用Linq在lambda表達式中的哪個子實體?

public class User 
{ 
    public int Id {get; set;} 
    public string Name {get; set;} 
    public virtual ICollection<UserProperty> Properties {get; set;} 
} 

public class UserProperty 
{ 
    public int Id {get; set;} 
    public int UserId {get; set;} 
    public int PropertyId {get; set;} 
    public virtual User User {get; set;} 
    public virtual Property Property {get; set;} 
} 

public class Property 
{ 
    public int Id {get; set;} 
    public string Name {get; set;} 
    public bool IsActive {get; set;} 
} 

我有倉庫方法:

public virtual IQueryable<User> Get(Expression<Func<User, bool>> predicate, params Expression<Func<User, object>>[] include) 
{ 
    var set = include.Aggregate<Expression<Func<User, object>>, IQueryable<User>> 
       (dbSet, (current, expression) => current.Include(expression)); 

    return set.Where(predicate); 
} 

我試圖讓用戶屬性,其中屬性IsActive是真實的名單,所以我做的:

public IEnumerable<UserProperty> GetSearches(int userId) 
{ 
    return userRepository.Get(x => x.Id == userId, 
           x => x.Properties.Where(p => p.Property.IsActive).Select(p => p.Property)).Properties; 
} 

不過,我得到這個異常:

包含路徑表達式必須引用在該類型上定義的導航屬性。對於參考導航屬性使用虛線路徑,對集合導航屬性使用Select運算符。參數名稱:路徑

我在做什麼錯?

編輯

以下替代作品:

return userRepository.Get(x => x.Id == userId, 
          x => x.Properties.Select(p => p.Property)).Properties.Where(p => p.Property.IsActive); 

然而,其中不包括在SQL語句的分貝條款,但所有的記錄都已經被檢索後執行。

我想限制直接在db中檢索到的記錄數。

+0

也許這將有助於http://stackoverflow.com/questions/16798796/ef-include-with-where-條款 –

回答

1

我會做簡單的東西:

public IEnumerable<UserProperty> GetSearches(int userId) 
{ 
    return userRepository.Where(x => x.Id == userId).Select(x => x.Properties.Where(p => p.IsActive)).Single(); //I assumed userId is unique 
} 

如果你需要更多的集團用戶的屬性,然後使用一個GroupBy

+0

我想使用上面的存儲庫方法。 UserRepository不是IDbSet,而是從通用存儲庫繼承的類。 –

+0

那麼你應該能夠從IEOumerable或IQueryable獲得一個表。 –

+0

'Select(p.Properties.Where(x => x.IsActive))'不能編譯。 –