Linq-to-entity с предложением where возвращает 0 записей в ASP. NET Web API, но тот же код работает в linkpad5 с возвращенными значениями. - PullRequest
0 голосов
/ 29 февраля 2020

У меня есть функция веб-API, которая вызывает другую функцию (в другом проекте в решении с именем services), которая выполняет хранимую процедуру. Эта функция веб-API возвращает ноль данных, если я использую предложение where (это требование для фильтрации моих данных) при отладке в VS, но если я использую тот же код в Linqpad для проверки запроса linq to entity, то она возвращает данные на основе мой пункт где. Я не могу понять, почему он не работает в приложении ASP. NET Web API.

Функция SalesAPIController

private readonly ISalesServices _salesServices;

public SalesController(ISalesServices salesServices)
{
    _salesServices = salesServices; 
}

[Route("GetProductSubCategories")]
[HttpGet]
[EnableCors("*", "*", "GET")]
public HttpResponseMessage GetProductSubCategories(string selectedProductCategory)
{
    IEnumerable<SalesByGeoResultDTO> salesForCountries = GetSalesCountries();

    if (salesForCountries != null)
    {
        if (salesForCountries.Any())
        {
            var mainSubCatTable = salesForCountries.Select(item => 
                            new { item.ProductSubCategoryKey, item.EnglishProductSubcategoryName, item.EnglishProductCategoryName }).AsQueryable().ToList();
            var records = mainSubCatTable .ToList().Where(item => item.EnglishProductCategoryName === (selectedProductCategory.Trim()))
                                .GroupBy(item => new
                            { item.ProductSubCategoryKey, item.EnglishProductSubcategoryName })
                                .Select(grouping => new
                                {
                                    grouping.Key.ProductSubCategoryKey,
                                    grouping.Key.EnglishProductSubcategoryName,
                                }).ToList();

            return Request.CreateResponse(HttpStatusCode.OK, records);
        }
    }

    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Product Category not found");
}

Итак, вышеприведенная функция возвращает данные в mainSubCatTable с этой строкой

var mainSubCatTable = salesForCountries.Select(item => 
                            new { item.ProductSubCategoryKey, item.EnglishProductSubcategoryName,item.EnglishProductCategoryName }).AsQueryable().ToList();

Но после этой записи возвращается 0.

private IEnumerable<SalesByGeoResultDTO> GetSalesCountries()
{
    IEnumerable<SalesByGeoResultDTO> salesForCountries = null;

    if (System.Web.HttpContext.Current != null)
    {
        if (HttpContext.Current.Session["salesForAllCountries"] != null)
        {
            salesForCountries = (IEnumerable<SalesByGeoResultDTO>)(HttpContext.Current.Session["salesForAllCountries"]);
        }
        else
        {
            salesForCountries = _salesServices.GetSalesForAllCountries("Country");
        }
    }
    else
    {
        salesForCountries = _salesServices.GetSalesForAllCountries("Country");
    }

    return salesForCountries;
}

SalesServices проект имеет функцию GetSalesForAllCountries (которая вызывается из API)

public IEnumerable<SalesByGeoResultDTO> GetSalesForAllCountries(string geoLevel)
{
    string query = "exec [ReportingSystemDB].[dbo].[SalesByGeography] @GeoLevel";

    SqlParameter geographyLevel = new SqlParameter("GeoLevel", SqlDbType.NVarChar) { Value = geoLevel };

    var salesForCountries = _unitOfWork.SalesByGeoRepository.ExecWithStoreProcedureSingleParams(
                 query, geographyLevel).ToList();

    if (salesForCountries.Any())
    {
        var salesForAllCountries = salesForCountries.Select(p => Mapper.Map<SalesByGeoResultDTO>(p)).ToList();

        if (HttpContext.Current == null)
        {
            HttpContext.Current.Session["salesForAllCountries"] = salesForAllCountries;
        }
        else
        {
            if (HttpContext.Current.Session != null)
                HttpContext.Current.Session["salesForAllCountries"] = salesForAllCountries;
        }

        return salesForAllCountries.ToList();
    }

    return Enumerable.Empty<SalesByGeoResultDTO>();
}

Итак, я взял коды из сервисов и функцию API, чтобы выполнить его в linqPad5, и он работает по возвращение данных из условия where.

Вот код linqpad, связывающий мои сущности dll

        void Main()
        {
            string geoLevel="country";
            var selectedProductCategory="Clothing";
            UnitOfWork _unitOfWork = new UnitOfWork();
            string query = "exec [ReportingSystemDB].[dbo].[SalesByGeography] @GeoLevel";
            SqlParameter geographyLevel = new SqlParameter("GeoLevel", SqlDbType.NVarChar) { Value = geoLevel };
            var salesForCountries =
                 _unitOfWork.SalesByGeoRepository.ExecWithStoreProcedureSingleParams(
                 query, geographyLevel).ToList();


             var mainCountryTable = salesForCountries.Select(item => 
                        new { item.ProductSubCategoryKey, item.EnglishProductSubcategoryName,item.EnglishProductCategoryName }).AsQueryable();
                        var records = mainCountryTable.ToList().Where(item => item.EnglishProductCategoryName==(selectedProductCategory.Trim()))
                            .GroupBy(item => new
                        { item.ProductSubCategoryKey, item.EnglishProductSubcategoryName })
                            .Select(grouping => new
                            {
                                grouping.Key.ProductSubCategoryKey,
                                grouping.Key.EnglishProductSubcategoryName,

                            }).ToList();

             records.ToList().Dump();
        }

, и результат показан здесь linqPad5 code returning data

Кажется, проблема в предложении where в коде функции api.

...