类型推断在对可空和非可空int的'join'调用中失败

man*_*der 9 c# linq entity-framework nullable non-nullable

在我的Linq中,我试图将内部联接设置为可以为空的字段.员工和部门有关系,部门可能有EmployeeID或者可能有null.那么什么是我的连接,如果我只想要满足内部连接的记录(没有结果为null EmployeeIDs):

var result = from emp in employees
             join dept in departments
             on new { Source = emp.EmployeeID }
             equals new { Source = dept.EmployeeID };
Run Code Online (Sandbox Code Playgroud)

我得到一个例外:

join子句中某个表达式的类型不正确.在"加入"调用中类型推断失败.

谢谢

Asb*_*erg 9

如果你改变你的加入并where在那里放一点怎么办?

var result = from department in departments
             where department.EmployeeID != null
             join employee in employees
             on department.EmployeeID.Value equals employee.EmployeeID
             select new { employee, department };
Run Code Online (Sandbox Code Playgroud)

  • @MSingh:你的代码与http://ideone.com/4F8X2的代码有什么不同?我想它应该是,因为你仍然得到错误. (3认同)
  • 这只是一个提示:为什么你使用"on new"和"equals new",对于单个比较器,你不需要使用语句"new",只需要"on"和"equals",`on department .EmployeeID.Value等于employee.EmployeeID` (3认同)

Gre*_*som 8

比较Int?和Int,附加.Value到可空属性:

var result = from emp in employees
             join dept in departments
             on new { Source = emp.EmployeeID }
             equals new { Source = dept.EmployeeID.Value };
Run Code Online (Sandbox Code Playgroud)

  • 请务必注意,您必须为添加“.Value”的名称命名,因为自动名称将是“Value”而不是“EmployeeID”。您可以(但不需要)为没有“.Value”的名称添加名称。因此,对于这个例子,“on new{emp.EmployeeID} equals new {EmployeeID = dept.EmployeeID.Value}”就可以了 (3认同)

tea*_*eng 5

从https://social.msdn.microsoft.com/Forums/en-US/bf98ec7a-cb80-4901-8eb2-3aa6636a4fde/linq-join-error-the-type-of-one- 的另一个链接中找到了有用的答案of-the-expressions-in-the-join-clause-is-incorrect-type-in​​ference?forum=linqprojectgeneral

要加入多值键,您需要在相同类型的“等于”的两侧构造一个匿名类型。匿名类型初始值设定项表达式从您提供的表达式中推断成员的类型和名称。在您的情况下,成员的名称不同,因此类型最终不同,因此 C# 无法确定两者之间的公共类型。

在 new { VC.Make, VC.Model } 上等于 new { MD.MakeID, MD.RefNum }

应该

on new { VC.Make, CV.Model } 等于 new { Make = MD.MakeID, Model = MD.RefNum }

在初始化程序中使用 name = value 语法,您可以指定编译器在创建类型时使用的名称。如果所有成员类型和名称都相同,则匿名类型是相同的类型。