在LINQ左的错误JOIN错误、LINQ、JOIN

2023-09-04 22:56:02 作者:听风行

我已经写了下面的查询在LINQ进行左连接,但其引发的错误:

i have written below query in LINQ to perform left join but its throwing error:

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 是空的。

cp.DefaultIfEmpty() returns a sequence which will have a single null value in if cp was empty.

这意味着你必须考虑到一个事实,即 P

That means you have to account for the fact that the p in

from p in cp.DefaultIfEmpty()

可能为空。现在,你还没有真正说过你希望发生在这种情况下什么。你可能会想是这样的:

may be null. Now, you haven't really said what you want to happen in that case. You might want something like this:

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_id p.value ,这不利于的类型。 (例如,你需要更多的工作与上面的code。如果的product_id 是值类型。)

... or you may want some different handling. We don't know the types of p.product_id or p.value, which doesn't help. (For example, you'll need a bit more work with the above code if product_id is a value type.)