Linq加入Null参考

时间:2014-03-26 20:12:10

标签: c# linq join

我的查询如下:

(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不为空,我该如何进行连接;以便获得我想要的数据而不会产生空引用异常?

类似的问题:Error in LINQ Left JOIN

1 个答案:

答案 0 :(得分:1)

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

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