即使使用 DefaultIfEmpty,Linq 查询也不会返回预期结果
Linq query not returning expected results even when using DefaultIfEmpty
我的 Entity Framework 核心 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
{ .. }
我需要它 return 所有行,即使 BookLinks 中不存在数据 table。
但是,如果 BookLinks table 中没有该行的数据数据,则不会 returning 行。
但是我试图从中建模的这个 SQL 查询确实 return 数据...如果 BookLinks 中没有数据,它 returns 为空。
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()' 应该可以解决这个问题,但没有。
我做错了什么?
谢谢!
当使用 left join 时,您可以尝试下面的代码示例:
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();
我的 Entity Framework 核心 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
{ .. }
我需要它 return 所有行,即使 BookLinks 中不存在数据 table。
但是,如果 BookLinks table 中没有该行的数据数据,则不会 returning 行。
但是我试图从中建模的这个 SQL 查询确实 return 数据...如果 BookLinks 中没有数据,它 returns 为空。
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()' 应该可以解决这个问题,但没有。
我做错了什么?
谢谢!
当使用 left join 时,您可以尝试下面的代码示例:
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();