1

我有一个查询如下:

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,从而使其成为左外连接而不是内连接。

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

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 匿名对象。

4

2 回答 2

4

为什么不使用三元运算符?

from p in (variable ? e.PractitionerProfiles : e.PractitionerProfiles.DefaultIfEmpty())
于 2015-06-15T04:52:40.227 回答
0

我通过在初始查询后添加过滤器来解决它,检查 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);
}
于 2015-06-18T00:14:47.920 回答