LINQ Left JOIN出错

我在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 in的事实

 from p in cp.DefaultIfEmpty() 

可能是null。 现在,你还没有真正说出你想要发生的事情。 你可能想要这样的东西:

 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.product_id的类型,这没有帮助。 (例如,如果product_id是值类型,则需要对上面的代码进行更多的工作。)

你正在进行左连接,所以p可以为null 。 你需要考虑到这一点。

这是应该工作的查询,虽然我不确定p.value是什么类型的值。 如果value是引用类型,则查询将起作用。 如果value是value类型,则使用类似于product_id cast的product_id

 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 ? (int?)null : p.product_id, value = p == null ? null : p.value, }; 

使用Model Class作为DefaultIfEmpty()函数的参数。

 from p in cp.DefaultIfEmpty(new yourModelClass())