【问题标题】:Linq query not returning expected results even when using DefaultIfEmpty即使使用 DefaultIfEmpty,Linq 查询也不返回预期结果
【发布时间】:2020-03-20 23:59:48
【问题描述】:

我的一个 Entity Framework Core API 控制器中有以下查询:

var plotData = await (from nl in _context.BookList
  join ql in _context.PlotList on nl.PlotId equals ql.PlotId
  join qc in _context.PlotChoices on ql.PlotId equals qc.PlotId
  join nk in _context.BookLinks.DefaultIfEmpty() on qc.ChoiceId equals nk.ChoiceId
  where nl.Id == ID
  select new
  { .. }

即使 BookLinks 表中不存在数据,我也需要它返回所有行。

但是,如果 BookLinks 表中没有该行的数据数据,则它不会返回行。

但是我试图从中建模的这个 SQL 查询确实返回数据...如果 BookLinks 中没有数据,它会返回空值。

select * from BookList bl
left join PlotList pl ON bl.plotId = bl.plotId
left join PlotChoices pc ON pl.plotId = pc.plotId
left join BookLinks bk ON pc.choiceID = bk.choiceID
where nl.caseID = '2abv1'

根据我在网上阅读的内容,将“DefaultIfEmpty()”添加到 BookLinks 的末尾应该可以解决这个问题,但它没有。

我做错了什么?

谢谢!

【问题讨论】:

  • BookLinks 是唯一没有记录的实体还是其他实体?
  • 也许我的SQL to LINQ Recipe 可以帮助你。

标签: linq asp.net-core entity-framework-core asp.net-core-2.0 iqueryable


【解决方案1】:

当使用左连接时,你可以试试下面的代码示例:

var plotData  = (from nl in _context.BookList
    join ql in _context.PlotList on nl.PlotId equals ql.PlotId
    join qc in _context.PlotChoices on ql.PlotId equals qc.PlotId
    join nk in _context.BookLinks on qc.ChoiceId equals nk.ChoiceId into Details
    from m in Details.DefaultIfEmpty()
    where nl.Id == ID
    select new
    {

    }).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 2019-11-11
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多