Entity Framework无外键两表左连接查询问题求助
Entity Framework左连接查询问题
我是Entity Framework新手,目前有两个实体类:
SynchronizationProfile
public class SynchronizationProfileDBEntity { public string SyncProfileId { get; set; } public string Code { get; set; } public SynchronizationType SyncType { get; set; } public string Schedule { get; set; } public string UserName { get; set; } }
SynchronizationLog
public class SynchronizationLogDBEntity { public string SyncLogId { get; set; } public string SyncProfileId { get; set; } public DateTime Ts { get; set; } public SyncLogStatus LogStatus { get; set; } }
团队没有给这两个实体设置外键,直接用LINQ查询。我需要获取SynchronizationLog的所有字段,再加上SynchronizationProfile中对应SyncProfileId的Code属性。尝试写了左连接的LINQ语句,但没得到预期结果,请问我的写法哪里错了?
我的LINQ代码如下:
var profiles = (from item in context.SynchronizationLogs join item2 in context.SynchronizationProfiles on item.SyncProfileId equals item2.SyncProfileId into gj from subitem in gj.DefaultIfEmpty() select new { SyncLogId = item.SyncLogId, SyncProfileId = item.SyncProfileId, Ts = item.Ts, LogStatus = item.LogStatus Code = item2.Code }
你的代码存在两个关键问题:
- 变量引用错误:左连接完成后,应该使用
subitem.Code而非item2.Code。item2是join子句里的源集合变量,而subitem才是左连接后(包含无匹配项的空值)的结果变量,当没有对应Profile记录时,subitem会为null,item2并不存在于后续逻辑中。 - 语法错误:
LogStatus = item.LogStatus末尾缺少逗号,会导致编译失败。
另外,由于是左连接,可能存在无对应Profile的Log记录,需要用subitem?.Code处理空引用情况。
修正后的代码:
var logsWithProfileCode = (from log in context.SynchronizationLogs join profile in context.SynchronizationProfiles on log.SyncProfileId equals profile.SyncProfileId into profileGroup from matchedProfile in profileGroup.DefaultIfEmpty() select new { SyncLogId = log.SyncLogId, SyncProfileId = log.SyncProfileId, Ts = log.Ts, LogStatus = log.LogStatus, Code = matchedProfile?.Code });
内容的提问来源于stack exchange,提问作者nick glav
相关产品推荐
相关产品推荐

