0

I have this code in my repository:

for (int i = startYear; i <= (endYear); i++)
{
    try
    {
        int varde = await _db.TomtbehovYear
                             .Where(m => m.Tomtbehov.Kommun.Namn == namn && m.Year == i)
                             .Select(m => m.Antal)
                             .SumAsync();

        listan.Add(varde);
    }
    catch
    {
        listan.Add(0);
    }
}

And my child component:

<td>@Area</td>
@foreach (var ant in Antal)
{
    <td>@ant</td>
}

@code {
    [Parameter]
    public string Area { get; set; } = null;

    [Parameter]
    public string AreaTyp { get; set; } = null;

    [Parameter]
    public int StartYear { get; set; } 

    [Parameter]
    public int EndYear { get; set; }

    private List<int> Antal = new List<int>();

    protected override async Task OnInitializedAsync()
    {
        Antal = await TomtbehovYearRepository.GetYearSumAsync(StartYear, EndYear, AreaTyp, Area);
    }

    protected override async Task OnParametersSetAsync()
    {
        Antal = await TomtbehovYearRepository.GetYearSumAsync(StartYear, EndYear, AreaTyp, Area);
    }
}

Parent :

    @if (raden.Kommun != Kommun)
    {
        Kommun = raden.Kommun;
        <tr class="table-info"><TomtBehovSumma Area="@Kommun" AreaTyp="Kommun" StartYear="@StartYear" EndYear="@EndYear" /></tr>
    }

But not every 'year' are calculated every time, some get value "0", if I refresh my page, some values that was "0" last time now is correct and others are "0".

I can't figure it out - what's wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Look for errors. `m.Tomtbehov.Kommun.Namn` could throw NRE, check your data. – H H Aug 27 '22 at 06:14
  • 2
    _"I can't figure it out - what's wrong?"_ Just remove `try catch` and check the error. – dani herrera Aug 28 '22 at 23:05
  • @HenkHolterman, yes, that's true. That's why I tried with try catch. What I can't figure out is why I get different result when I reload the page. But that's maybe wrong way to handle it. – Tobias Gustafsson Aug 29 '22 at 09:40
  • In catch block you are ignoring the exception. Change to `catch (Exception ex) { Console.WriteLine(ex.Message); }` and check what exception you are getting. – Dimitris Maragkos Aug 31 '22 at 18:24
  • I got no errors, just sum = 0... But I now think it has something to do with thread problems and db context. Alot of problems where solved by setting db context to transient. – Tobias Gustafsson Sep 02 '22 at 13:03

1 Answers1

0

Solved it by using this code instead :

sumPerYear = await _db.TomtbehovYear
                    .Include(t => t.Tomtbehov)
                    .Where(x => x.Tomtbehov.Kommun.Namn == namn)
                    .GroupBy(x => x.Year)
                    .Select(yearGroup => new
                    {
                        Year = yearGroup.Key,
                        sumPerYear = yearGroup.Sum(t => t.Antal)
                    })
                    .ToListAsync();