Home > Software engineering >  Linq - adding .Include(x=>Table) causes error 500
Linq - adding .Include(x=>Table) causes error 500

Time:10-30

I have a fairly straightforward database schema. I have a list of Cemeteries, each Cemetery may have a CountryId for where it's located. The majority are currently null. I am attempting to return a paged result.

If I do the below, it works perfectly fine, fast and paged. If I use the .Include, I can see the List<T> returned to the controller, and the controllers return sit to the API. The API however shows error 500.

public Shared.Models.Paging.PagedResult<Cemetery> List(int page, string filter)
{
    const int pageSize = 10;

    var data = _ctx.Cemeteries
                   // .Include(p => p.Country)
                   .AsNoTracking()
                   .AsQueryable();

    if (!string.IsNullOrEmpty(filter) && filter != "null")
    {
        data = data.Where(filter);
    }

    return data.GetPaged(page, pageSize);
}

public partial class Cemetery
{
    public int Id { get; set; }
    public string Name { get; set; } = null!;
    public int? CountryId { get; set; }
    public DateTime? CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }

    public virtual Country? Country { get; set; }
}

public partial class Country
{
    public Country()
    {
        Cemeteries = new HashSet<Cemetery>();
    }

    public int Id { get; set; }
    public string Name { get; set; } = null!;
    public DateTime? CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }

    public virtual ICollection<Cemetery> Cemeteries { get; set; }
}

If I place a try/catch in the code, all I get is an error 500, the server did not indicate success.

public async Task<PagedResult<CemeteryModel>> List(int page, string filter)
{
    var searchParams = $"/{page}?filter=";

    searchParams  = string.IsNullOrEmpty(filter) ? "null" : filter;

    return await _httpClient.GetFromJsonAsync<PagedResult<CemeteryModel>>($"api/Cemetery/List{searchParams}");
}

CodePudding user response:

A 500 means that there was an exception on the server, so you would need to debug the server code, not the client code (which is what you are doing at the moment).

Having said that, if filter is a string, then I'm surprised hat the following even compiles...

data = data.Where(filter);

...as, as far as I can see, Where doesn't have an overload that takes a string.

However, debugging the server code should reveal exactly what the problem is.

CodePudding user response:

The answer was I had a mapping issue in my controller from Cemetery to CemeteryModel

What I had

  CreateMap<Cemetery, CemeteryModel>().ReverseMap();

What I needed

  CreateMap<PagedResult<Cemetery>, PagedResult<CemeteryModel>>().ReverseMap();
  • Related