LINQ for an SQL with multiple LEFT OUTER JOINs on different tables
LINQ for an SQL with multiple LEFT OUTER JOINS on different tables
我正在尝试创建一个包含 LEFT 外连接的 LINQ 查询。有一些例子,但我有一些不同的情况[=12=]
Select * from A_TABLE
LEFT OUTER JOIN B_TABLE ON A_TABLE.Id = B_TABLE.A_TABLE_Id
LEFT OUTER JOIN C_TABLE ON B_TABLE.Id = C_TABLE.B_TABLE_Id
第二次加入不在 A_TABLE 上,它是 B_TABLE 和 C_TABLE
我们可以将其转换为 LINQ 吗?
您可以像这样简单地将查询转换为 linq 查询:
var results = (from a in A_TABLE
join b in B_TABLE
on a.A_TABLE_Id equals b.A_TABLE_Id into ab
from b in ab.DefaultIfEmpty()
join c in C_TABLE_List on b.B_TABLE_Id equals c.B_TABLE_Id
select new
{
ClassAProperty1 = a.Property1,
ClassBProperty1 = b.Property1,
ClassCProperty1 = c.Property1
}).ToList();
您可以随时继续加入表。
不要忘记将 属性# 更改为所需的 属性 名称。
有关更多信息,请查看 LINQ Left Outer Join, and this stack thread。
更新:
这是查询的 Lambda 表达式版本:
var result = A_TABLE
.GroupJoin(B_TABLE,
a => a.A_TABLE_Id,
b => b.A_TABLE_Id,
(a, b) =>
new {
tableAProperty1 = a.Property1,
tableAProperty2 = a.Property2, /* You cannot access this property in next join if you don't add it here */
B_TABLE = b.FirstOrDefault() /* This is the way to access B_TABLE in next join */
}).GroupJoin(C_TABLE,
ab => ab.B_TABLE.B_TABLE_Id,
c => c.B_TABLE_Id,
(ab, c) =>
new {
ab.tableAProperty1,
B_TABLEProperty2 = ab.B_TABLE.Property2,
C_TABLE = c.FirstOrDefault()
}).ToList();
我正在尝试创建一个包含 LEFT 外连接的 LINQ 查询。有一些例子,但我有一些不同的情况[=12=]
Select * from A_TABLE
LEFT OUTER JOIN B_TABLE ON A_TABLE.Id = B_TABLE.A_TABLE_Id
LEFT OUTER JOIN C_TABLE ON B_TABLE.Id = C_TABLE.B_TABLE_Id
第二次加入不在 A_TABLE 上,它是 B_TABLE 和 C_TABLE
我们可以将其转换为 LINQ 吗?
您可以像这样简单地将查询转换为 linq 查询:
var results = (from a in A_TABLE
join b in B_TABLE
on a.A_TABLE_Id equals b.A_TABLE_Id into ab
from b in ab.DefaultIfEmpty()
join c in C_TABLE_List on b.B_TABLE_Id equals c.B_TABLE_Id
select new
{
ClassAProperty1 = a.Property1,
ClassBProperty1 = b.Property1,
ClassCProperty1 = c.Property1
}).ToList();
您可以随时继续加入表。
不要忘记将 属性# 更改为所需的 属性 名称。
有关更多信息,请查看 LINQ Left Outer Join, and this stack thread。
更新: 这是查询的 Lambda 表达式版本:
var result = A_TABLE
.GroupJoin(B_TABLE,
a => a.A_TABLE_Id,
b => b.A_TABLE_Id,
(a, b) =>
new {
tableAProperty1 = a.Property1,
tableAProperty2 = a.Property2, /* You cannot access this property in next join if you don't add it here */
B_TABLE = b.FirstOrDefault() /* This is the way to access B_TABLE in next join */
}).GroupJoin(C_TABLE,
ab => ab.B_TABLE.B_TABLE_Id,
c => c.B_TABLE_Id,
(ab, c) =>
new {
ab.tableAProperty1,
B_TABLEProperty2 = ab.B_TABLE.Property2,
C_TABLE = c.FirstOrDefault()
}).ToList();