C# 如何编写LINQ以左连接分组依据的表?
我有一个SQL Server查询:C# 如何编写LINQ以左连接分组依据的表?,c#,.net,linq,C#,.net,Linq,我有一个SQL Server查询: SELECT * FROM ENotes en LEFT JOIN ( SELECT ENoteId, ReadByUId, [Read] FROM [ENotesReadBies] WHERE ReadByUId = 1173 AND [Read] = 1 GROUP BY ENoteId, ReadByUId, [Read] ) A ON (en.ENoteId = A.ENoteId) 如何为它编写LINQ?我知道我可以
SELECT *
FROM ENotes en LEFT JOIN (
SELECT ENoteId, ReadByUId, [Read]
FROM [ENotesReadBies]
WHERE ReadByUId = 1173 AND [Read] = 1
GROUP BY ENoteId, ReadByUId, [Read]
) A ON (en.ENoteId = A.ENoteId)
如何为它编写LINQ?我知道我可以这样离开加入:
from x in _context.ENotes
join erb in _context.ENotesReadBies on x.ENoteId equals erb.ENoteId
into tempReadBy
from rb in tempReadBy.Where(x => x.ReadByUId == 1173 && x.Read == true).DefaultIfEmpty()
但这并不意味着这一群体的存在
谢谢让我们这样做:
var groupPart = from erb in _context.ENotesReadBies
where erb.ReadByUId == 1173 && erb.Read
group erb by new { erb.ENoteId, erb.ReadByUId, erb.Read } into grouped
select new
{
grouped.Key.ENoteId,
grouped.Key.ReadByUId,
grouped.Key.Read
};
var result = from e in _context.ENotes
join g in groupPart
on e.ENoteId equals g.ENoteId into gJ
from g in gJ.DefaultIfEmpty()
select new
{
ENote = e,
g.ENoteId,
g.ReadByUId,
g.Read
};
var materializedResult = result.ToList();
如果运行此代码并分析其生成的sql查询,您将得到:
SELECT [e].[ENoteId], [e].[Name], [t].[ENoteId], [t].[ReadByUId], [t].[Read]
FROM [ENotes] AS [e]
LEFT JOIN (
SELECT [e0].[ENoteId], [e0].[ReadByUId], [e0].[Read]
FROM [ENotesReadBies] AS [e0]
WHERE ([e0].[ReadByUId] = CAST(1173 AS bigint)) AND ([e0].[Read] = CAST(1 AS bit))
GROUP BY [e0].[ENoteId], [e0].[ReadByUId], [e0].[Read]
) AS [t] ON [e].[ENoteId] = [t].[ENoteId]
这和你想要的一样;) 您正在使用.NETCore3吗?