SELECT A.X, B.Y
FROM A JOIN B ON A.X = B.Y
此 linq 方法调用(对 Join)将生成上述 Join。
var query = A.Join
(
B,
a => a.x,
b => b.y,
(a, b) => new {a.x, b.y} //if you want more columns - add them here.
);
SELECT A.X, B.Y
FROM A LEFT JOIN B ON A.X = B.Y
这些 linq 方法调用(对 GroupJoin、SelectMany、DefaultIfEmpty)将产生上面的 Left Join
var query = A.GroupJoin
(
B,
a => a.x,
b => b.y,
(a, g) => new {a, g}
).SelectMany
(
z => z.g.DefaultIfEmpty(),
(z, b) =>
new { x = z.a.x, y = b.y } //if you want more columns - add them here.
);
这里的关键概念是 Linq 的方法产生分层形状的结果,而不是扁平的行列形状。
- Linq's
GroupBy
生成以层次结构形式形成的结果,其中分组键与收藏元素(可能不为空)。 SQL 的GroupBy
子句产生一个分组键合计值- 没有可以使用的子集合。
- 同样,Linq 的
GroupJoin
产生一个分层形状 - 父记录与收藏子记录(可能为空)。 sql的LEFT JOIN
生成与每个子记录匹配的父记录,如果没有其他匹配,则生成空子记录。要从 Linq 的形状到达 Sql 的形状,必须使用以下命令解压子记录集合SelectMany
- 并使用处理空子记录集合DefaultIfEmpty
.
这是我尝试对问题中的 sql 进行解析:
var query =
from a in Appointment
where a.RowStatus == 1
where a.Type == 1
from b in a.AppointmentFormula.Where(af => af.RowStatus == 1).DefaultIfEmpty()
from d in a.TypeRecord //a has a type column and is related to a table named type, disambiguate the names
from e in a.AppointmentForm.DefaultIfEmpty()
order by a.Type
select new { a.AppointmentId, a.Status, a.Type, a.Title, b.Days, d.Description, e.Form }