NullReferenceException в SubSonic 2.2 RecordBase.cs после запроса Json.Зачем? - PullRequest
0 голосов
/ 31 мая 2011

У меня есть проект MVC, который использует службу WCF.Служба возвращает коллекцию местоположений, которая используется для фильтрации автозаполнения в текстовом поле.

Сначала я попытался сделать это с помощью своего собственного объекта "Person", чтобы убедиться, что все это работает.

jQuery call:

    $(function () {

        $("#txtGeoLocation").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/home/FindLocations", type: "POST", dataType: "json",
                    data: { searchText: request.term, maxResults: 10 },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.FullName, value: item.FullName, id: item.PersonId }
                            // return { label: item.GeoDisplay, value: item.GeoDisplay, id: item.GeoID }
                        }))
                    }
                })
            },
            select: function (event, ui) {
                alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
                    : "Nothing selected, input was " + this.value);
            }
        });

    });

Действие контроллера:

    [HttpPost]
    public JsonResult FindNames(string searchText, int maxResults)
    {
        PersonRepository repository = new PersonRepository();
        var result = repository.FindPeople(searchText, maxResults);
        return Json(result);

    }

Репозиторий Person:

public class PersonRepository
{


    internal List<Person> FindPeople(string searchText, int maxResults)
    {

        List<Person> names = new List<Person>();

        BuildNameList(names);


        var result = from n in names
                     where n.FullName.Contains(searchText)
                     orderby n.FullName
                     select n;

        return result.Take(maxResults).ToList(); 
    }

    private static void BuildNameList(List<Person> names)
    {
        names.Add(new Person { PersonId = 1, FullName = "Kristina H. Chung" });
        names.Add(new Person { PersonId = 2, FullName = "Paige H. Chen" });
        names.Add(new Person { PersonId = 3, FullName = "Sherri E. Melton" });

Работал отлично ... поэтому я заменилмой вызов Json из / home / FindNames в / home / FindLocations и раскомментировал следующую строку (закомментировав строку item.FullName в моем вызове jQuery):

return { label: item.GeoDisplay, value: item.GeoDisplay, id: item.GeoID }

Вот мое действие контроллера:

    [HttpPost]
    public JsonResult FindLocations(string searchText, int maxResults)
    {
        GeoLocationRepository repository = new GeoLocationRepository();
        var result = repository.FindGeo(searchText, maxResults);

        return Json(result);    // returned a list collection of geo locations
    }

Мой метод хранилища:

    internal List<FeederService.GeoLocation> FindGeo(string searchText, int maxResults)
    {
        // get geolocations from the cache

        var result = from l in HttpRuntime.Cache["WebsiteGeoLocations"] as FeederService.GeoLocationCollection
                     where l.GeoDisplay.Contains(searchText)
                     orderby l.GeoDisplay
                     select l;

        return result.Take(maxResults).ToList();
    }

Кажется, что все работает нормально до конца метода действия:

return Json(result);    // returned a list collection of geo locations

На самом деле существует правильная коллекция снужное количество предметов в нем, но ничего не вернулось моему клиенту.VS всплывает с файлом SubSonic RecordBase.cs и исключением нулевой ссылки при вызове get публичной строки TableName:

    /// <summary>
    /// Name of the table in the database that contains persisted data for this type
    /// </summary>
    /// <value>The name of the table.</value>
    [XmlIgnore]
    [HiddenForDataBinding(true)]
    public string TableName
    {
        get { return BaseSchema.TableName; }  // <--- error occurs here
    }

Это происходит из-за некоторой проблемы со ссылкой на сущность, поскольку я ссылаюсь на FeederService.Объект GeoLocation и как я могу заставить это работать?

Все сущности находятся в проекте DAL, на которые ссылаются и предоставляют через мой FeederService: GeoLocationCollection [CollectionDataContract]

[Serializable]
[CollectionDataContract]
public partial class GeoLocationCollection : ActiveList<GeoLocation, GeoLocationCollection>
{      
    public GeoLocationCollection() {}

And I 'я добавил [DataContract] в GeoLocation.

Я также поместил «отладчик»;в моем коде jquery (перенес его в функцию), но я не могу отладить возвращенные данные.Как я могу это сделать?

Наконец, проблема возникает только в случае совпадения в коллекции.

1 Ответ

0 голосов
/ 31 мая 2011

Мне удалось решить эту проблему, хотя и не так элегантно, как хотелось бы, и я все же хотел бы знать, почему у меня возникают проблемы со ссылкой на класс, предоставляемый через мой сервис.

ДляВ качестве решения я создал класс модели WebsiteGeoLocation, который имеет некоторые свойства класса FeederService.GeoLocation.

Затем я провел итерацию по коллекции и скопировал значения в мой новый локальный объект.Работает просто отлично.Я перенесу функцию копирования в метод кэширования, поэтому возвращаемый объект всегда имеет локальный тип.

    List<WebsiteGeoLocation> geoList = null;

    internal List<WebsiteGeoLocation> FindGeo(string searchText, int maxResults)
    {
        // get geolocations from the cache

        var result = from l in HttpRuntime.Cache["WebsiteGeoLocations"] as FeederService.GeoLocationCollection
                     where l.GeoDisplay.Contains(searchText)
                     orderby l.GeoDisplay
                     select l;

        geoList = new List<WebsiteGeoLocation>();

        foreach (FeederService.GeoLocation location in result)
        {
            geoList.Add(new WebsiteGeoLocation
            {
                GeoID = location.GeoID,
                GeoDisplay = location.GeoDisplay,
                GeoCity = location.GeoCity,
                GeoState = location.GeoState,
                WebsiteID = location.WebsiteID,
                WorldCitiesID = location.WorldCitiesID
            });
        }

        return geoList.Take(maxResults).ToList();
    }
...