我有这个型号:
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为true的用户属性列表,所以我正在做:
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;
}
然而,我得到了这个例外:
Include路径表达式必须引用在类型上定义的导航属性。使用虚线路径作为参考导航属性,使用Select运算符作为集合导航属性。参数名称:路径
我做错了什么?
修改
以下替代方案有效:
return userRepository.Get(x => x.Id == userId,
x => x.Properties.Select(p => p.Property)).Properties.Where(p => p.Property.IsActive);
但是,where子句不包含在db语句的SQL语句中,而是在检索完所有记录后执行。
我想限制直接在db中检索的记录数。
答案 0 :(得分: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。