我有這樣的模式:使用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中檢索到的記錄數。
也許這將有助於http://stackoverflow.com/questions/16798796/ef-include-with-where-條款 –