2014-03-26 48 views
2

我的查询如下:LINQ的加入空引用

(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

尝试增加,其中legalRate.HostCountryId = null来查询! – Andrew

回答

1

您可以使用DefaultIfEmpty构造方法设置你的legalRate的默认值:

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