如何编写实体的LINQ以加入空表 [英] How to write an LINQ for entities for joining empty tables
问题描述
我有两张桌子:
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
以上sql在SQL Server上执行时就是结果。
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
我为上述查询尝试了这个LINQ:
请注意:scats上下文表是一个空表。
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();
返回NullReferenceException。
我尝试过:
<根据以下链接中的建议尝试使用DefaultIfEmpty():$ / b
https://www.codeproject.com/ articles / 169590 / linq-to-sql-left-join-with-null-values
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.
推荐答案
修改查询以包含空检查,这很好。
推荐: C#中的101个LINQ样本 [ ^ ]
修改后的LINQ查询突出显示更改:
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();
这篇关于如何编写实体的LINQ以加入空表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!