【问题标题】:Using multiple LINQ statements with into , for the DefaultIfEmpty() of the left outer join not working使用多个带有 into 的 LINQ 语句,因为左外连接的 DefaultIfEmpty() 不起作用
【发布时间】:2019-11-08 02:25:58
【问题描述】:

我正在尝试使用带有 DefaultIfEmpty() 的“into”语句进行左外连接,但是当我尝试加入第三个集合时,它不喜欢它(看不到/使用它/找到它)

下面一行的personRole好像不太喜欢

join roleTypes in roles on personRole.ContactRoleTypeId equals roleTypes.ContactRoleTypeId into r2

查询:

findPersonResultsViewModelNew =
         from azed in findPersonViewModel.findPersonResultsViewModel
         join personRole in personContactRoles on azed.PersonID equals personRole.PersonId into r1
         join roleTypes in roles on personRole.ContactRoleTypeId equals roleTypes.ContactRoleTypeId into r2
         from p in r1.DefaultIfEmpty()
         from g in r2.DefaultIfEmpty()
         select
         //…. other code 

【问题讨论】:

  • 您的订单很重要。一旦你做了into r1personRole 就不再存在了。如果您想离开加入并使用personRole 跟随,您必须立即执行from personRole in r1.DefaultIfEmpty()。见我的SQL to LINQ Recipe

标签: c# .net linq collections linq-to-sql


【解决方案1】:

更改语句的顺序。进行左连接时,您必须立即在join 后面加上一个新的from...DefaultIfEmpty()

findPersonResultsViewModelNew =
         from azed in findPersonViewModel.findPersonResultsViewModel
         join personRole in personContactRoles on azed.PersonID equals personRole.PersonId into prj
         from personRole in prj.DefaultIfEmpty()
         join roleTypes in roles on personRole.ContactRoleTypeId equals roleTypes.ContactRoleTypeId into rtj
         from roleTypes in rtj.DefaultIfEmpty()
         select

【讨论】:

  • 实际上,在最后一次加入时,我在 personRole.ContactRoleTypeId 上得到了一个空引用异常。想法?
  • 如果您使用不应该发生的 LINQ to SQL/EF,但如果您使用 LINQ to Objects,则需要 personRole?.ContactRoleTypeId,因为 personRole 可能是 null 如果没有什么可以加入的。
猜你喜欢
  • 2013-02-04
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-14
  • 1970-01-01
相关资源
最近更新 更多