如何使用Join in LINQ重写两个表的SQL Union?

时间:2014-01-31 19:34:17

标签: c# linq

我有3个课程如下:

public class A
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string Age {get; set;}
    public bool IsEmployed {get; set;}
    public int RoleId {get; set;}
}

public class B
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string Age {get; set;}
    public int RoleId {get; set;}
}

public class Roles
{
    public int Id {get; set;}
    public string RoleName {get; set;}
    ...
}

假设这些类在DBMS上有自己的表。

我目前有一个SQL查询,我想在LINQ中重写(尽可能优雅)

SELECT A.Name, A.Age, Roles.RoleName, A.IsEmployed 
FROM A 
JOIN Roles ON A.RoleId = Roles.Id
WHERE Roles.RoleName = 'ADMIN'

UNION

SELECT B.Name, B.Age, Roles.RoleName, '-' as IsEmployed 
FROM B 
JOIN Roles ON B.RoleId = Roles.Id
WHERE Roles.RoleName = 'ADMIN'

目前我已设法将其重写为:

var filteredClassA = from c in allClassAs
    join role in allRoles on role.Id equals c.RoleId
    where role.RoleName == "ADMIN"
    SELECT new {c.Name, c.Age, role.RoleName, c.IsEmployed};

var filteredClassB = from c in allClassBs
    join role in allRoles on role.Id equals c.RoleId
    where role.RoleName == "ADMIN"
    SELECT new {c.Name, c.Age, role.RoleName, IsEmployed = "-"};

然后我可以将结果连接或组合成一个变量,如下所示:

var result = filteredClassA.Union(filteredClassB);

我不喜欢这个解决方案,有没有更好的方法在单个LINQ查询中完成上述所有操作?

提前致谢。

2 个答案:

答案 0 :(得分:4)

另一个选项,只在一个查询中:

var result = allClassAs.Join(allRoles, c => c.Id, role => role.Id, (c, role) => new {c.Name, c.Age, role.RoleName, c.IsEmployed})
                        .Where(r => r.RoleName == "ADMIN")
                        .Union(allClassBs.Join(allRoles, c => c.Id, role => role.Id, (c, role) => new {c.Name, c.Age, role.RoleName, IsEmployed = "-"})
                        .Where(r => r.RoleName == "ADMIN"));

答案 1 :(得分:1)

(from a in context.A
where a.Roles.Any(r=>r.RoleName == "ADMIN")
select new {Name = a.Name, Age = a.Age, Role = "ADMIN", Employed = a.IsEmployed})
.Union(
from b in context.B
where b.Roles.Any(r=>r.RoleName == "ADMIN")
select new {Name = b.Name, Age = b.Age, Role = "ADMIN".RoleName, Employed = "-"}
)