Linq Join子句类型错误排查:类型推断失败问题求助
LINQ Join类型推断失败问题解决
问题代码
var model = await (from a in _context.Mfemployees join b in _context.Mfclients on a.MfemployeeClientCode equals b.MfclientCode into ab from x in ab.DefaultIfEmpty() join c in _context.Mujls on new { a.MfemployeeGroup, a.MfemployeeEmploymentLevel } equals new { MujlGroup = c.MujlGroup, MujlLevel = c.MujlLevel } select new ExportPartiesDTO { MFEMPLOYEEGroup = a.MfemployeeGroup, MFEMPLOYEEEmployeeCode = a.MfemployeeEmployeeCode ?? "", MFEMPLOYEEEmploymentDate = a.MfemployeeEmploymentDate, MFCLIENTName = x.MfclientName ?? "", MFCLIENTSurname = x.MfclientSurname ?? "", MFCLIENTPhone = x.MfclientPhone ?? "", MFCLIENTHP = x.MfclientHp ?? "", MFCLIENTEmail = x.MfclientEmail ?? "" }).ToListAsync(cancellationToken);
报错信息
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to join.
已确认关联字段均为String类型,但报错依旧。
问题根源
LINQ的join操作要求用于匹配的匿名类型属性名称、顺序、类型完全一致。你在第二条join的右侧匿名类型中给属性设置了别名(MujlGroup、MujlLevel),但左侧匿名类型的属性名是MfemployeeGroup、MfemployeeEmploymentLevel,两边属性名不匹配,导致编译器无法推断出这两个匿名类型是同一类型,进而报错。
修复方案
只需让两边匿名类型的属性名称一致即可,两种方式任选:
方式1:右侧使用左侧的属性名
join c in _context.Mujls on new { a.MfemployeeGroup, a.MfemployeeEmploymentLevel } equals new { MfemployeeGroup = c.MujlGroup, MfemployeeEmploymentLevel = c.MujlLevel }
方式2:左侧使用右侧的属性名
join c in _context.Mujls on new { MujlGroup = a.MfemployeeGroup, MujlLevel = a.MfemployeeEmploymentLevel } equals new { c.MujlGroup, c.MujlLevel }
修改后编译器就能正确识别匿名类型,join操作可以正常执行。
内容的提问来源于stack exchange,提问作者Haminteu
相关产品推荐
相关产品推荐

