Search code examples
c#botframeworkazure-cognitive-search

Azure Search SearchParameters Object reference not set to an instance of an object error


I am trying to add search fields to my Azure Search query (see below instantiation of the SearchParameters object).

    public async Task StartAsync(IDialogContext context)
    {
        ISearchIndexClient indexClient = CreateSearchIndexClient();
        try
        {
            Trace.TraceInformation($"Starting StartAsync");
            SearchParameters searchParameters = new SearchParameters();
            searchParameters.SearchFields.Add("StoreNumber");
            searchParameters.SearchFields.Add("StoreName");
            Trace.TraceInformation($"Finished adding search fields");
           // Trace.TraceInformation($"Search Parameters added = {searchParameters.SearchFields.Count}");

            DocumentSearchResult results = await indexClient.Documents.SearchAsync(searchText, searchParameters);
            Trace.TraceInformation($"results obtained");

            List<SearchHit> searchHits = results.Results.Select(r => ResultMapper.ToSearchHit(r)).ToList();
            Trace.TraceInformation($"search hits {searchHits.Count}");
            await SendResultsOfSearch(context, results);
        }
        catch (Exception ex)
        {
            Trace.TraceError($"Exception {ex.ToString()}");
        }
    }

For some reason it's throwing the following exception but I have no idea why?

2018-09-03T00:47:39  PID[3268] Information Starting StartAsync
2018-09-03T00:47:39  PID[3268] Error       Exception System.NullReferenceException: Object reference not set to an instance of an object.
   at LuisBot.Dialogs.SearchRBMDialog.<StartAsync>d__2.MoveNext() in C:\Users\jmatson\Downloads\retail-info-bot-v2-src\Dialogs\SearchRBMDialog.cs:line 32

The code compiles fine? And there are no constructor arguments required as far as I know.


Solution

  • SearchFields is not initialized by the SearchParameters constructor (see the source code here), so calling Add on it will result in NullReferenceException. It's of type IList, so the easiest way to initialize it is by assigning an array to it, like this:

    searchParameters.SearchFields = new[] { "StoreNumber", "StoreName" };