簡體   English   中英

LINQ的左外部聯接運行時錯誤

[英]Left outer join runtime error with LINQ

我正在嘗試在2個表上用Linq編寫一個左外部聯接查詢,但是在右表中有空值的情況下,運行時會得到NULL引用異常。

對於tbl_Match表中的所有MatchID值,tbl_UserBets表沒有所有值。 因此,當出現NULL值時,我得到了運行時異常

PFB我的LINQ查詢,

string userID = "dfa3c0e7-2aa3-42ee-a7d3-803db902dc56";
var res2 = dbEntity.tbl_Match.Select(m => new
            {
                MatchID = m.MatchID,
                Team1 = m.Team1,
                Team2 = m.Team2,
                UserForTeam1 = dbEntity.tbl_UserBets.Where(b => b.UserForTeam1 == userID).FirstOrDefault(b => b.MatchID == m.MatchID),
                UserForTeam2 = dbEntity.tbl_UserBets.Where(b => b.UserForTeam2 == userID).FirstOrDefault(b => b.MatchID == m.MatchID)
            });

            foreach (var item in res2)
            {
                Console.WriteLine(item.MatchID + " " + item.Team1 + " vs " + item.Team2 + " " + item.UserForTeam1 == null ? " NA " : item.UserForTeam1.UserForTeam1);
            }

tbl_Match表的SQL表設計:

Create Table tbl_Match(
MatchID int primary key Identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
Team1 int Foreign key references tbl_TournamentTeams(TeamID),
Team2 int Foreign key references tbl_TournamentTeams(TeamID),
StartTime DateTime not null,
MatchBetAmount int not null
);

tbl_UserBets表的SQL表設計:

Create Table tbl_UserBets(
UserBetSlNo int primary key identity,
TournamentID int Foreign key references tbl_Tournament(TournamentID),
MatchID int Foreign key references tbl_Match(MatchID),
UserForTeam1 nvarchar(128) Foreign key references AspNetUsers(Id),
UserForTeam2 nvarchar(128) Foreign key references AspNetUsers(Id),
UserForNoBets nvarchar(128) Foreign key references AspNetUsers(Id)
);

使用下面的SQL查詢,我可以正確獲取結果,需要對LINQ進行相同的操作。

select DISTINCT(tbl_Match.MatchID),tbl_Match.Team1,tbl_Match.Team2,tbl_Match.StartTime,tbl_Match.MatchBetAmount,tbl_UserBets.UserForTeam1,tbl_UserBets.UserForTeam2,tbl_UserBets.UserForNoBets from tbl_Match left outer join tbl_UserBets on tbl_Match.MatchID = tbl_UserBets.MatchID and (tbl_UserBets.UserForTeam1 = 'dfa3c0e7-2aa3-42ee-a7d3-803db902dc56' or tbl_UserBets.UserForTeam2 = 'dfa3c0e7-2aa3-42ee-a7d3-803db902dc56')

請讓我知道,我應該怎么做才能解決此問題。 謝謝。

嘗試將where條件與第一個或默認值合並

我猜問題是當where返回null時,第一個或默認值將導致msdn doc所述的異常

var res2 = dbEntity.tbl_Match.Select(m => new
            {
                MatchID = m.MatchID,
                Team1 = m.Team1,
                Team2 = m.Team2,
                UserForTeam1 = dbEntity.tbl_UserBets.FirstOrDefault(b => b.UserForTeam1 == userID && b.MatchID == m.MatchID),
                UserForTeam2 = dbEntity.tbl_UserBets.FirstOrDefault(b => b.UserForTeam2 == userID && b.MatchID == m.MatchID)
            });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM