2014-03-26 47 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 })