0

I have a problem. I am getting the sum of a certain column from the database. However, in some cases the sum should be 0 -> if there are no records that meet the criteria

In the view I have:

<Label Content="{Binding Path=Sum, UpdateSourceTrigger=PropertyChanged}" />

In ViewModel I have:

public override void save()
{
    Sum = new Sum(ATMAEntites).Calculate(IdEvent, IdDealer, "Standing");      
}

In the model class I have:

public int? Calculate(int IdEvent, int IdDealer, string CategoryName)
{
    return (from wydaneSprzedawcy in ATMAEntites.WydaneSprzedawcy
            where wydaneSprzedawcy.Bilety.IdEvent == IdEvent &&
                  wydaneSprzedawcy.IdDealer == IdDealer &&
                  wydaneSprzedawcy.Bilety.CategoryName == CategoryName
            select wydaneSprzedawcy.quantity).Sum();
}

I want check in the model whether the query returns null

1
  • your code will gives you 0 if no record match the where expression, but if ATMAEntites.WydaneSprzedawcy gives you sometimes null value, add test before enter in the loop like : return ATMAEntites.WydaneSprzedawcy == null ? 0 : (....) Mar 1, 2020 at 11:01

1 Answer 1

0

I assume, that wydaneSprzedawcy.quantity is int and not nullable. Then you can try adding a cast to (int?) in the select, like this:

public int? Calculate(int IdEvent, int IdDealer, string CategoryName)
{
    return
        (
            from wydaneSprzedawcy in ATMAEntites.WydaneSprzedawcy
            where
                wydaneSprzedawcy.Bilety.IdEvent == IdEvent &&
                wydaneSprzedawcy.IdDealer == IdDealer &&
                wydaneSprzedawcy.Bilety.CategoryName == CategoryName
            select (int?)wydaneSprzedawcy.quantity
        ).Sum();
}

Now, if the query returns no records, sum should return null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.