关于c#:Linq Join Null参考

Linq Join Null Reference

我的查询如下:

1
2
3
4
5
(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 [...]

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

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

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

1
from legalRate in countryRates.DefaultIfEmpty()

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

类似的问题:LINQ中的错误Left Join


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

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