0

我正在尝试从一些数据完整性不高的数据库中导入地址数据。因此,有许多地址(甚至在美国)没有邮政编码,并且它们被读取为 NULL。

我正在尝试将这些地址与现有的干净地址数据库进行一些匹配。我根据收件人(公司名称)、州(区)、城市(地区)和 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();

每当潜在地址为空时,我都会不断收到错误消息。我越来越:

Object reference not set to an instance of an object

当查询生成器尝试解析 potentialAddress.SubString(..) 时。

如果一个或另一个(或两者)为空,我不想通过邮政编码将其称为匹配项。

有任何想法吗?

4

1 回答 1

0

似乎问题与评估查询中的 potentialAddress 对象有关。IOW,a.PostalCode != null 被评估,一个 false 值将停止对该条件的任何进一步处理,而 potentialAddress.PostalCode != null 似乎被忽略并且语句的评估继续 - 当它到达潜在地址时导致错误。 PostalCode.SubString(0,5)。

我解决这个问题的唯一方法是将处理潜在地址的条件代码移到查询之外。

所以,我现在有这样的事情:

if(potentialAddress.PostalCode == null || potentialAddress.PostalCode.Length < 5)
    //Perform query that ignores postal code
else
    //Perform query that performs substring of postal code comparison
endif

如果我能在查询本身中做到这一切,当然会很好。也许有人可以解释为什么查询中对 potentialAddress.PostalCode 的评估似乎不起作用。

于 2012-11-01T14:30:07.377 回答