c# - 使用 Entity Framework Core 的 LEFT JOIN 查询
问题描述
我做了很多研究并阅读了一些类似的问题和答案,但仍然不知道如何编写 EF Core 代码来创建以下 SQL 服务器查询。有人可以帮忙吗。我看过教程解释如何使用 LEFT JOIN 连接 2 个表,但找不到包含 3 个或更多表的任何内容。
SELECT std.DocID, std.ServiceCode,
CASE std.Description
WHEN 'Car Wash'
THEN 'Misc'
ELSE std.Description
END AS 'Description',
std.StandardRate, std.StandardHours,
det.ParticipantCount, det.TotalHours, det.TotalFees
FROM StandardServices std
INNER JOIN Sorted srt
ON std.ServiceCode = srt.ServiceCode
LEFT OUTER JOIN ServiceDetails det
ON det.ParentRecordUNID='00000000-0000-0000-0000-000000000000' AND det.ServiceTypeUNID=std.DocID
WHERE std.IsDeleted='N' AND std.TopService = 'Y'
ORDER BY srt.SortOrder
以下是接近上述内容的内容(出于隐私考虑,我已经替换了一些文本,因此可能不完全匹配)。但由于某些原因,它选择了所有列而不是提到的列。此外,它在末尾添加了一个 (SELECT 1)。
var results=await (from sso in context.StandardServices
join mos in context.Sorted on sso.ServiceCode equals mos.ServiceCode
join mad in context.ServiceDetails
on new { key1 = sso.DocID, key2 = parentId } equals new { key1 = (Guid)mad.ServiceTypeUnid, key2 = mad.ParentRecordUnid }
into jointable
where sso.IsDeleted == "N" && sso.TopService =="Y"
orderby mos.SortOrder
from mad1 in jointable.DefaultIfEmpty()
select new ServiceRowDetails()
{
DocID = mad1.DocID,
ParentRecordUnid = mad1.ParentRecordUnid,
ServiceTypeUnid = sso.DocID,
ServiceType = sso.Description,
ParticipantCount = mad1.ParticipantCount ?? 0,
StandardFees = sso.StandardRate ?? 0,
StandardHours = sso.StandardHours ?? 0,
TotalFees = mad1.TotalFees ?? 0,
TotalHours = mad1.TotalHours ?? 0
}).ToListAsync();
更新:正如@IvanStoev 在下面评论的那样进行了更改,效果很好。
var results=await (from sso in context.StandardServices
join mos in context.Sorted on sso.ServiceCode equals mos.ServiceCode
join mad in context.ServiceDetails
on new { key1 = sso.DocID, key2 = parentId } equals new { key1 = (Guid)mad.ServiceTypeUnid, key2 = mad.ParentRecordUnid }
into jointable
from mad1 in jointable.DefaultIfEmpty()
where sso.IsDeleted == "N" && sso.TopService =="Y"
orderby mos.SortOrder
select new ServiceRowDetails()
{
DocID = mad1.DocID,
ParentRecordUnid = mad1.ParentRecordUnid,
ServiceTypeUnid = sso.DocID,
ServiceType = sso.Description,
ParticipantCount = mad1.ParticipantCount ?? 0,
StandardFees = sso.StandardRate ?? 0,
StandardHours = sso.StandardHours ?? 0,
TotalFees = mad1.TotalFees ?? 0,
TotalHours = mad1.TotalHours ?? 0
}).ToListAsync();
解决方案
推荐阅读
- ios - 如何使 UIAlertController 中的右侧按钮变为粗体?
- python - Python3客户端套接字接收到的消息不完整
- android - 这是创建重复背景 IntentService 的适当方法吗?
- python - Python - 使用字符串作为表达式(exec 和 eval 不起作用)
- angular - 如何在 Web 应用程序中预览 EML 文件?
- java - Android:如何让活动调用类
- asp.net-mvc - 预检请求在 IIS 中不起作用
- java - 创建了两个条件 While 循环,一个条件与另一个条件一样会导致无限循环
- java - 如何在 JAVA 中使用 XMLDecoder 反序列化 XML
- c# - 我想要一个在 y 轴上倾斜的对象沿着 Z 轴移动?