我一直在打开和关闭这个,我真的不知道我做错了什么或者这是EF Core的错误,基本上问题是我的查询有两个连接总是返回零结果,我尝试以各种不同的方式重写它无济于事(我只是得到各种不同的错误)并且如果它只是一个错误我不想继续战斗它。但是,查询在LINQPad中按预期工作。查询如下:
var playerholder = (from player in db.Players
join assignment in db.TeamAssignments on player.PlayerID equals assignment.PlayerID into assignments
from assignment in assignments.DefaultIfEmpty()
join team in db.Teams on assignment == null ? 0 : assignment.TeamID equals team.TeamID into teams
from team in teams.DefaultIfEmpty()
select new PlayerListItem_PDVMI
{
PlayerID = player.PlayerID,
FirstName = player.FirstName,
LastName = player.LastName,
TeamName = (assignment == null ? "Not Assigned" : team.Name)
}).ToList();
如果玩家可以拥有0个或更多TeamAssignments,而TeamAssignment只有一个团队。
从我的日志文件中生成的SQL。这也可以直接在数据库上运行时正常运行:
SELECT [assignment].[ID], [assignment].[PlayerID], [assignment].[PlayerNumber], [assignment].[Position], [assignment].[SeasonID], [assignment].[TeamID], [player].[PlayerID], [player].[FirstName], [player].[LastName]
FROM [Players] AS [player]
LEFT JOIN [TeamAssignments] AS [assignment] ON [player].[PlayerID] = [assignment].[PlayerID]
ORDER BY [player].[PlayerID]
并且紧接着就是对Teams表的查询:
SELECT [assignment.Team].[TeamID], [assignment.Team].[Name]
FROM [Teams] AS [assignment.Team]
这是我的TeamAssignment类(删除了不相关的属性):
public class TeamAssignment : IModel
{
[Key]
public int ID { get; set; }
public int PlayerID { get; set; }
public int TeamID { get; set; }
[ForeignKey("PlayerID")]
public virtual Player Player { get; set; }
[ForeignKey("TeamID")]
public virtual Team Team { get; set; }
}
小组:
public class Team : IModel
{
[Key]
public int TeamID { get; set; }
public string Name { get; set; }
public virtual ICollection<TeamAssignment> CurrentPlayers { get; set; }
}
播放器:
public class Player : IModel
{
[Key]
public int PlayerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<TeamAssignment> TeamAssignments { get; set; }
}