我需要使用method / fluent语法在Linq中等效这个SQL语句。
SELECT u.[UserId], s.[UserId], d.[UserId]
FROM dbo.[Attachment] z
INNER JOIN dbo.[Activity] a ON z.[ActivityId] = a.[ActivityId]
INNER JOIN dbo.[Case] c ON a.[CaseId] = c.[CaseId]
INNER JOIN dbo.[CaseUser] x ON c.[CaseId] = x.[CaseId]
INNER JOIN dbo.[User] u ON x.[UserId] = u.[UserId]
LEFT OUTER JOIN dbo.[User] s ON u.[SupervisorId] = s.[UserId]
LEFT OUTER JOIN dbo.[User] d ON s.[SupervisorId] = d.[UserId]
WHERE u.[UserId] = @x OR s.[UserId] = @x OR d.[UserId] = @x
另外,我在必须返回System.Linq.Expressions.Expression对象的上下文中使用它。例如,现有的更简单代码的示例是:
public override Expression<Func<Attachment, bool>> MatchingCriteria
{
get { return a => a.Activity.Case.CaseUsers.Any(x => (x.User.Id == this.id)); }
}
我被左连接所困扰,使用的方法语法评估为bool。
答案 0 :(得分:1)
我认为以下内容应该有效...您检查以确保模型中的相关实体不为空,然后进行比较,如果不是:
return a => a.Activity.Case.CaseUsers
.Where(cu => cu.User.Id == this.id ||
(cu.User.Supervisor != null &&
cu.User.Supervisor.Id == this.Id) ||
(cu.User.Supervisor != null &&
cu.User.Supervisor.Supervisor != null &&
cu.User.Supervisor.Supervisor.Id == this.Id));
答案 1 :(得分:1)
使用以下方法,您既可以检查是否存在任何一个必需的Id,也可以选择该项目。
使用样本类定义,如:
class Foo
{
public int FirstBarId { get; set; }
public int SecondBarId { get; set; }
}
class Bar
{
public int BarId { get; set; }
}
您可以查询:
var query = fooSet.Select(foo => new
{
Foo = foo,
Bar1 = barSet.FirstOrDefault(bar => foo.FirstBarId == bar.BarId),
Bar2 = barSet.FirstOrDefault(bar => foo.SecondBarId == bar.BarId)
})
.Where(x => x.Bar1 != null || x.Bar2 != null);