Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have two tables :

Category(categ) 
Sub Category (scat)

I want to perform the following query on the above tables.
select a.code, a.name, a.type, b.category as category from categ a left join scat b on a.code=b.code


The above sql when executed on SQL Server this is the result.

code     name      type    category
1001     abc       F       NULL
1002     def       F       NULL
1003     ghi       B       NULL  


I tried this LINQ for the above query :
Please note : The scats context table is an empty table.

List<categscat> lstcateg = (from categrow in Context.categs.AsEnumerable()
                            join scatrow in Context.scats
                            on categrow.code equals scatrow.code                             
                            select new categscat(categrow.code, categrow.name, 
                            categrow.type, categrow.cate, 
                            joinedrow.category)).ToList();



This returns a NullReferenceException.

What I have tried:

tried using the DefaultIfEmpty() as per suggestions in the link below :

https://www.codeproject.com/articles/169590/linq-to-sql-left-join-with-null-values

lstcateg = (from categrow in dlsmain.odlsContext.categs.AsEnumerable()
                            join scatrow in dlsmain.odlsContext.scats.AsEnumerable()
                            on categrow.code equals scatrow.code into jointable
                            from joinedrow in jointable.DefaultIfEmpty()
                            select new categscat(categrow.code, categrow.name, categrow.type, categrow.cate, joinedrow.category)).ToList();


Still I'm getting the same error. What is my mistake? How to get this right ? Please suggest.
Posted
Updated 12-Feb-19 20:53pm
v2

1 solution

Revised the query to include a null check and it was fine.

Referred : 101 LINQ Samples in C#[^]

Revised LINQ query with the change highlighted :

lstcateg = (from categrow in dlsmain.odlsContext.categs.AsEnumerable()
                           join scatrow in dlsmain.odlsContext.scats.AsEnumerable()
                           on categrow.code equals scatrow.code into jointable
                           from joinedrow in jointable.DefaultIfEmpty()
                           select new categscat(categrow.code, categrow.name, categrow.type, categrow.cate, joinedrow == null ? "" : joinedrow.category)).ToList();
 
Share this answer
 
Comments
Maciej Los 13-Feb-19 15:41pm    
Worth a 5!
Priya-Kiko 14-Feb-19 0:09am    
Thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900