我是sql查詢我們產生正確的結果,但是當我在LINQ中做同樣的事情。輸出不正確。請讓我知道我犯了什麼錯誤。LINQ多表左連接,不同的計數沒有給出正確的結果
以下是我創建的linq查詢。
LINQ查詢:
List<UserModel> Model = (from users in db.UserMasters
join ct in db.CustTests on users.UserId equals ct.UserID into group1
from g1 in group1.DefaultIfEmpty()
join ti in db.TestInvitaions on g1.TestId equals ti.TestID into group2
from g2 in group2.DefaultIfEmpty()
where (users.CustomerId==UserSession.CustomerId) && (users.RoleId == 4) && (users.Status == 1)
group new
{
g2.TestInvitationID,
g2.TestID,
}
by new
{
users.FirstName,
users.CreatedOn,
users.Email,
users.UserId
} into group4
select new UserModel
{
Name = group4.Key.FirstName,
CreatedOn = group4.Key.CreatedOn,
EmailId = group4.Key.Email,
UserId = group4.Key.UserId,
NoOfTestTaken = group4.Select(x=>x.TestID).Distinct().Count(),
NoOfInvitationsSent = group4.Count(x => x.TestInvitationID != 0)
}).ToList();
SQL查詢:
SELECT IsNull(COUNT(distinct TS.TestId),0) AS NoOfTests,
IsNull(COUNT(TS.TestInvitationID),0) AS NoOfInvitations,
UM.Email,
UM.UserId,
UM.FirstName,
UM.CreatedOn
FROM UserMaster as UM
left JOIN CustTest AS CT
ON UM.UserId=CT.UserId
left JOIN TestInvitaions AS TS
ON TS.TestId = CT.TestId
WHERE UM.CustomerId=41
AND UM.RoleId=4
and UM.[Status]=1
GROUP BY UM.UserId, UM.Email, UM.FirstName, UM.CreatedOn
表:
- 「UserMaster」 - 列:用戶ID,電子郵件,名字,CreatedOn
- 「CustTest 「 - 列:TestId,UserId,
- 「TestInvitaions」 - 列:TestInvitationId,TestId
是sql查詢洙給出正確的結果......根據該參考PLZ回答 – Gaurry
請解釋一下你得到什麼你並沒有期待。一些示例數據和預期的輸出也會有幫助 –
我的sql查詢是正確的soo plz使它成爲LINQ – Gaurry