【问题标题】:Linq Conditional DefaultIfEmpty query filterLinq 条件 DefaultIfEmpty 查询过滤器
【发布时间】:2015-06-18 08:14:47
【问题描述】:

我有一个查询如下:

bool variable = false//or true


var query = from e in _repository.GetAll<Entity>()
            from u in e.Users
            where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId
            from p in e.PractitionerProfiles.DefaultIfEmpty()
            select new { entity = e, user = u, profile = p };

这可以正常工作。但是,我有一个布尔变量,它应该确定与 e.PractitionerProfiles 的连接是否应该具有 DefaultIfEmpty,从而使其成为左外连接而不是内连接。

但是,由于我使用的是令人讨厌的对象,我无法弄清楚如何正确地做到这一点。所以我希望能够在 Left 和 Inner Join 之间切换,而无需复制整个查询,例如:

if(variable) {
            var query = from e in _repository.GetAll<Entity>()
                        from u in e.Users
                        where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId
                        from p in e.PractitionerProfiles
                        select new { entity = e, user = u, profile = p };
}
else {
            var query = from e in _repository.GetAll<Entity>()
                        from u in e.Users
                        where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId
                        from p in e.PractitionerProfiles.DefaultIfEmpty()
                        select new { entity = e, user = u, profile = p };
}

有没有一种简洁的方法可以通过一个查询来完成?问题还在于我有许多进一步的条件,因此在循环内声明查询意味着它没有局部变量,我不知道如何创建一个空的 IQueryable 匿名对象。

【问题讨论】:

  • 我现在不能尝试这个,但是你可以使用三级运算符内联吗? DefaultIfEmpty 应该与您调用它的序列具有相同的类型。
  • 查看下面出现的错误
  • 啊,EF 不知道如何处理它。除非您愿意预先从数据库中恢复整个 PractitionerProfiles 集合,否则我认为您的复制/粘贴查询将是您最好的选择

标签: c# linq asp.net-mvc-5 linq-query-syntax


【解决方案1】:

为什么不用三元运算符?

from p in (variable ? e.PractitionerProfiles : e.PractitionerProfiles.DefaultIfEmpty())

【讨论】:

  • 我收到以下错误:'不支持嵌套查询。 Operation1='案例' Operation2='收集''
  • @RhysStephens:尝试在查询之外获取配置文件。也许之前列举过它们。
【解决方案2】:

我通过在初始查询后添加过滤器来解决它,检查 e.PractitionerProfiles 是否为空。

    var query = from e in _repository.GetAll<Entity>()
                from u in e.Users
                where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId
                from p in e.PractitionerProfiles.DefaultIfEmpty()
                select new { entity = e, user = u, profile = p };

然后

if (variable)
{
    query = query.Where(x => x.profile != null);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多