Linq查询即使使用DefaultIfEmpty也不返回预期结果

问题描述 投票:0回答:1

我在一个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中没有数据,则返回null。

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'

从我在网上阅读的内容来看,在BookLinks的末尾添加'DefaultIfEmpty()'应该可以解决此问题,但是还没有。

我在做什么错?

谢谢!

linq asp.net-core entity-framework-core asp.net-core-2.0 iqueryable
1个回答
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();
© www.soinside.com 2019 - 2024. All rights reserved.