我試圖從一些沒有太多數據完整性的數據庫導入地址數據。所以有很多地址(甚至在美國)沒有郵政編碼,並且它們被讀入爲NULL。如何查詢linq to sql的可爲空的varchar的子字符串?
我想要對現有的乾淨的地址數據庫做一些這些地址匹配。我根據收件人(公司名稱),州(地區),城市(地區)和Street1或郵政編碼的前5位確定匹配。
我嘗試這樣做:
//This is just coded for the example -- In my routine, potentialAddress
//is coming from a data source where Postal Code may or may not be null.
Address potentialAddress = new Address() {
Street1 = "2324 Lakeview Drive",
PostalCode = null,
CountryId = 234, //US
Locality = "Sanford",
District = "FL"
};
//What I want here is Country & District have to match and either
//Street matches OR (if this is a US address) the first 5 of the postal code matches
_context.Addresses.Where(a => ((a.Street1 == potentialAddress.Street1)
|| (a.PostalCode != null && potentialAddress.PostalCode != null && potentialAddress.PostalCode.SubString(0,5) == a.PostalCode.SubString(0,5))
&& a.CountryId == potentialAddress.CountryId
&& a.District == potentialAddress.District).Select(a => a.Id).ToList();
我不斷收到錯誤消息時potentialAddress爲空。我得到:
Object reference not set to an instance of an object
當查詢生成器試圖解析potentialAddress.SubString(..)。
如果其中一個或其他(或兩者)爲空,我不想通過郵政編碼將其稱爲匹配。
任何想法?
找到了解決方案,但沒有解釋問題。 – RHarris