pravprab pravprab - 25 days ago 7
C# Question

null reference exception on using DefaultIfEmpty()

I wrote the below sql query

SELECT *

FROM dbo.PR_ADDRESS LEFT OUTER JOIN
dbo.Book_MarkText ON dbo.PR_ADDRESS.GroupID = dbo.Book_MarkText.BMData
where
dbo.PR_ADDRESS.GroupID = dbo.Book_MarkText.BMData

OR
PR_ADDRESS.GroupID in ('001','002','003')


to LINQ as

string[] srGroupIDs = new string[] { "001", "002", "003" };
var objResult =
(from PR_ADDRESS in dtPR_ADDRESS.AsEnumerable()
join
Book_MarkText in dtBookmarkText.AsEnumerable() on
(string)PR_ADDRESS["GroupID"] equals (string)Book_MarkText["BMData"]
into Book_MarkText_join

from Book_MarkText_Temp in Book_MarkText_join.DefaultIfEmpty()
where srGroupIDs.Contains(PR_ADDRESS["Groupid"])
|| ((string)PR_ADDRESS["Groupid"] == (string)Book_MarkText_Temp["BMData"])

select new
{
ID = PR_ADDRESS["ID"],
Name1 = PR_ADDRESS["Name1"]
}).ToList();


But Gives me null reference exception on line

where srGroupIDs.Contains(PR_ADDRESS["Groupid"])
|| ((string)PR_ADDRESS ["Groupid"] == (string)Book_MarkText_Temp["BMData"])


Why ?

If i remove
.DefaultIfEmpty()
, this works without exception , but i need 'LEFT OUTER JOIN' so can't remove
.DefaultIfEmpty()
. How can i solve it ?

Edit :-

I added the OR case also , Hope now it is clear

Answer

Solved by handling Book_MarkText_Temp null as Jon Skeet's comment .Thanks for finding time to help me .

 string[] srGroupIDs =  new string[] { "001", "002", "003" };

var objResult =
        (from PR_ADDRESS in dtPR_ADDRESS.AsEnumerable() 
                join
             Book_MarkText in dtBookmarkText.AsEnumerable() on
            (string)PR_ADDRESS ["GroupID"] equals (string)Book_MarkText["BMData"] into Book_MarkText_join

    from Book_MarkText_Temp in Book_MarkText_join.DefaultIfEmpty()                      
    where Book_MarkText_Temp == null ? srGroupIDs.Contains(PR_ADDRESS["Groupid"]) :

    srGroupIDs.Contains(PR_ADDRESS["Groupid"])
    || ((string)PR_ADDRESS["Groupid"] == (string)Book_MarkText_Temp["BMData"])

    select new {
                  ID = PR_ADDRESS ["ID"],
                  Name1 = PR_ADDRESS ["Name1"]
                }).ToList();