在 C# 上使用 where 条件子句与 linq 进行左/外连接

Jos*_*osh 5 c# linq sql-server left-join asp.net-core-2.0

我有 2 个表需要加入查询。第一个表是条目表,其中包含某些事件,例如舞蹈、说话、唱歌、播放等。

Id|Name  
   1|Dance  
   2|Sing  
   3|Speak  
   4|Play  
   5| etc.
Run Code Online (Sandbox Code Playgroud)

另一个表包含 userEntries,它指示每个用户在每个事件上的分数

Id| UserId|EntryId|Score

 1|898128 | 1     |200

 2|827329 | 2     |120

 3|898128 | 2     |100
Run Code Online (Sandbox Code Playgroud)

现在我想要一个 linq 查询,首先获取所有条目,然后获取给定用户的分数,为条目重新调整 null 为用户有 noscore 的条目分数

用户 898128 的示例,我想看到这样的内容

Dance:200,Speak:null,Sing:120 从结果

我尝试了以下 linq 查询,但结果为空

var userScores = 
(from e in db.Entries join se in db.UserEntries
on e.Id equals se.EntryId                                           
into ese from se in 
ese.DefaultIfEmpty()
where se.UserId == "898128"
select new 
{
EntryLabel=e.Label,
EntryValue=se.ValueAmount,
}).ToList();

ViewData["userScores "] = userScores;
Run Code Online (Sandbox Code Playgroud)

我在 ASP.NET 核心 2.0 上运行,实体框架核心在带有 Visual Studio 2017 15.6.3 的 Windows 10 机器上

我将不胜感激任何获得正确查询的指南,以便为我提供外部联接,这样即使用户没有任何分数,我也可以获得每个用户的所有条目。

请注意,这是从不同这个问题,通过errorneously标记@Mahmoud作为它的副本。不同之处在于 WHERE 条件子句的存在。

谢谢

Jos*_*osh 4

我已经从这个SO问题找到了答案。从那里,我意识到 where 子句的位置是问题所在。请参阅下面的工作代码修订版

var userScores = 
(from e in db.Entries join se in db.UserEntries.Where(o => o.UserId == 
"898128" 
on e.Id equals se.EntryId                                           
into ese from se in 
ese.DefaultIfEmpty()
select new 
{
EntryLabel=e.Label,
EntryValue=se.ValueAmount,
}).ToList();

ViewData["userScores "] = userScores;
Run Code Online (Sandbox Code Playgroud)

谢谢@Hazarath的指导