我的查询如下:

(from c in countries
 join r in Db.PaymentRates_VisaImmigrationPermit on c.CountryId equals r.HomeCountryId into countryRates
 from legalRate in countryRates.DefaultIfEmpty()
 join hostC in Db.Countries on legalRate.HostCountryId equals hostC.Id
 select new [...]


我在此行上得到一个空引用异常:

join hostC in Db.Countries on legalRate.HostCountryId equals hostC.Id


...这显然是由以下行引起的:

from legalRate in countryRates.DefaultIfEmpty()


仅当legalRate不为null时,才能进行联接;以获取我想要的数据而不会引起null引用异常?

类似的问题:Error in LINQ Left JOIN

最佳答案

您可以使用legalRate构造函数设置DefaultIfEmpty的默认值:

 from legalRate in
     countryRates.DefaultIfEmpty(new CountryRate { HostCountryId = int.MaxValue })

10-06 12:03