c# - LINQ 左 JOIN 错误

标签 c# .net linq .net-3.5 linq-to-objects

我已经在 LINQ 中编写了下面的查询来执行左连接但它抛出错误:

var qry = from c in dc.category_feature_Name_trans_SelectAll_Active()
          join p in dc.product_category_feature_trans_SelectAll()
          on c.cft_id equals p.cft_id into cp
          from p in cp.DefaultIfEmpty()                      
          select new
          {
              c.cft_id,
              c.feature_id,
              c.feature_name,
              p.product_id ,
              p.value 
          };

错误:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the 
current web request. Please review the stack trace for more information about
the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 57:                       on c.cft_id equals p.cft_id into cp
Line 58:                       from p in cp.DefaultIfEmpty()                      
error Line 59:                       select new
Line 60:                       {
Line 61:                           c.cft_id,

请帮帮我。

最佳答案

cp.DefaultIfEmpty() 返回一个序列,如果 cp 为空,该序列将具有单个空值。

这意味着你必须考虑到 p

from p in cp.DefaultIfEmpty()

可以为空。现在,您还没有真正说出您希望在那种情况下发生什么。你可能想要这样的东西:

var qry = from c in dc.category_feature_Name_trans_SelectAll_Active()
          join p in dc.product_category_feature_trans_SelectAll()
          on c.cft_id equals p.cft_id into cp
          from p in cp.DefaultIfEmpty()                      
          select new
          {
              c.cft_id,
              c.feature_id,
              c.feature_name,
              product_id = p == null ? null : p.product_id,
              value = p == null ? null : p.value 
          };

... 或者您可能需要一些不同的处理方式。我们不知道 p.product_idp.value 的类型,这无济于事。 (例如,如果 product_id 是值类型,则您需要对上述代码进行更多操作。)

关于c# - LINQ 左 JOIN 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6106537/

相关文章:

c# - 了解 TaskScheduler.Current 的行为

.net - 为什么 .Net 词典会调整为质数?

c# - 在多维数组中查找值并返回所有项目 c#

c# - group by 操作包含无法翻译的表达式

c# - 将键值与 LinQ 分开

c# - 我应该将我的应用程序上下文与用于标识的 ApplicationDbContext 分开吗?

c# - EntityRef 和编译的 LINQ 计划

c# - 必须初始化隐式类型的局部变量

c# - 统一: GameObject repeated instantiation issue

c# - 即使已设置,变量也会导致 NullReferenceException