【问题标题】:Use Linq Where on child entity in lambda expression?在 lambda 表达式中的子实体上使用 Linq Where?
【发布时间】:2015-04-22 17:12:42
【问题描述】:

我有这个模型:

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;
}

但是,我遇到了这个异常:

包含路径表达式必须引用在类型上定义的导航属性。对引用导航属性使用虚线路径,对集合导航属性使用 Select 运算符。参数名称:路径

我做错了什么?

编辑

以下替代作品:

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

但是,where子句不包含在对db的SQL语句中,而是在检索到所有记录后执行。

我想限制直接在数据库中检索的记录数。

【问题讨论】:

标签: c# linq lambda


【解决方案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

【讨论】:

  • 我想使用上面的存储库方法。 UserRepository 不是 IDbSet,而是从通用存储库继承的类。
  • 那么你应该能够从 repo 中获取一个 IEnumerable 或 IQueryable 的表。
  • Select(p.Properties.Where(x =&gt; x.IsActive)) 无法编译。
猜你喜欢
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
相关资源
最近更新 更多