Behdadsoft
Behdadsoft

Reputation: 77

Linq check value in SQL table always is false

I tried to check if the cost or benefit value exists for the selected Id, then I will get the cost or benefit value from the table. In the code below my if statement doesn't work and seems to always be false but the return benefit value works fine. Where is the problem?

    public string GetCostBenefitAmount(int id)
    {
        if (db.CostBenefits.Any(c => c.ID == id && !c.Cost.Equals(0)))
        {
            return db.CostBenefits.Select(c => c.Cost).First().ToString();
        }
        return db.CostBenefits.Where(c=> c.ID == id).Select(c => c.Benefit).First().ToString();
    }

This is my code in windows form for fill txtAmount textBox by GetCostBenefitAmount(int id) method:

            var stockIdList = db.CostBenefitRepository.GetAllID();                
            int id = stockIdList[listBox.SelectedIndex];
            CostBenefit costBenefit = db.GenericCostBenefitRepository.GetById(id);
            txtStockName.Text = listBox.SelectedItem.ToString();
            txtSoldAmount.Text = costBenefit.SoldAmount.ToString();
            ComboCostBenefit.SelectedItem = db.CostBenefitRepository.GetCostBenefitOperation(id);
            txtAmount.Text = db.CostBenefitRepository.GetCostBenefitAmount(id);

Upvotes: 0

Views: 69

Answers (2)

Yosef Bernal
Yosef Bernal

Reputation: 1064

The Object.Equals method determines whether two object instances are equal. Try if (db.CostBenefits.Any(c => c.ID == id && c.Cost != 0)). For more info on the Object.Equals function see this post.

Edit: As @Gert Arnold commented, the issue was in the return db.CostBenefits.Select(c => c.Cost).First().ToString(); where there was no filtering done before returning.

Upvotes: 3

Salik Rafiq
Salik Rafiq

Reputation: 184

I think equals is only when you are using in a join. So just use

c.Cost != 0

instead.

Upvotes: 0

Related Questions