[英]Use Linq Where on child entity in lambda expression?
我有这个模型:
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;
}
但是,我收到此异常:
包含路径表达式必须引用在类型上定义的导航属性。 使用虚线路径作为参考导航属性,使用“选择”运算符作为集合导航属性。 参数名称:路径
我究竟做错了什么?
编辑
以下替代作品:
return userRepository.Get(x => x.Id == userId,
x => x.Properties.Select(p => p.Property)).Properties.Where(p => p.Property.IsActive);
但是,where子句不包含在db的SQL语句中,而是在检索到所有记录之后执行。
我想限制直接在数据库中检索的记录数。
我会做一些简单的事情:
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 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.