Linq查询“对象引用未设置为对象的实例”

时间:2012-09-25 21:38:44

标签: linq

我有2个简单的Web服务方法来查询我通过javascript查询的XML文档(存储在HTTP缓存中)。当我为aff参数传递一个完全有效的数据项时,GetCitiesForAffiliate()方法在“select new”行上抛出NullReferenceException。它适用于aff参数中的其他数据。另一种方法也可以正常工作,即使使用相同的aff参数导致另一种方法爆炸。

我刚刚验证了我要查询的XML。当我传入一个不存在的aff时,这两种方法只返回一个空的json字符串,这没关系。我应该看哪些可能是错的?

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetCitiesForAffiliate(string aff)
    {
        LocationService loc = new LocationService();
        var query = (from center in loc.centersXml.Descendants("Center")
                     where center.Element("ServiceArea").Value.Equals(aff)
                     select new {
                         City = center.Element("City").Value
                     }).Distinct().OrderBy(x => x.City);

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string json = serializer.Serialize(query);

        return json;
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetCentersForAffiliateCity(string aff, string city)
    {
        LocationService loc = new LocationService();
        var query = (from center in loc.centersXml.Descendants("Center")
                     where center.Element("ServiceArea").Value.Equals(aff) && center.Element("City").Value.Equals(city)
                     select new { 
                         ID = center.Element("ID").Value,
                         Name = center.Element("Name").Value 
                     }).Distinct().OrderBy(x => x.Name);

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string json = serializer.Serialize(query);

        return json;
    }

1 个答案:

答案 0 :(得分:5)

如果您的某些节点缺少City元素,那么您有一些选择,具体取决于您想要的输出:

1)添加一项检查以查看City元素是否为null

City = (center.Element("City") == null ? null : center.Element("City").Value)

2)添加where子句以忽略具有空城市的元素:

where center.Element("ServiceArea").Value.Equals(aff) 
    and center.Element("City") != null