I’m trying to import address data from some a database where there was not much data integrity. So there are a number of addresses (even in the US) that don’t have postal codes and they’re being read in as NULL.
I’m trying to do some matching of these addresses against an existing clean address database. I’m determining matches based on Addressee (company name), State (District), City (Locality) and either Street1 OR the first 5 of the postal code.
I tried this:
//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();
I’m constantly getting an error message whenever potentialAddress is null. I’m getting:
Object reference not set to an instance of an object
when the query generator tries to parse potentialAddress.SubString(..).
I don’t want to call it a match by postal code if one or the other (or both) are null.
Any ideas?
It seems as though the issue had to do with evaluating the potentialAddress object within the query. IOW, a.PostalCode != null was evaluated and a false value would stop any further processing of the condition whereas potentialAddress.PostalCode != null seemed to be ignored and the evaluation of the statement continued — causing an error when it hit potentialAddress.PostalCode.SubString(0,5).
The only way I got around this was to move the conditional code dealing with potentialAddress outside of the query.
So, I now have something like this:
Sure would’ve been nice if I could do that all in the query itself. Maybe someone could explain why the evaluation of potentialAddress.PostalCode in the query doesn’t seem to work.