Rasika Rasika - 2 months ago 12
C# Question

How to get sum of two column values from SQL table using Entity Framework?

enter image description here

I have a table name

GRNDtlReturn
in above mention screenshot. I want to get the sum of
ReturnQuantity
of first and third rows in table. I have written some code, but it returns the sum of full
ReturnQuantity
column. Please help me to solve this.

Here's my code:

public IList<GRNDtlReturnModel> GetReturnSum()
{
return igrndtlreturnRepository.GetList (x=> x.GRNNo == "GRN00022" && x.ProductCode == "D/F/HL/DM/0003/C/002")
.Select(y => new GRNDtlReturnModel
{
GRNNo = y.GRNNo,
totalQuantity = context.GRNDtlReturns.Sum(p => p.ReturnQuantity)
}).ToList();
}

Answer
public IList<GRNDtlReturnModel> GetReturnSum()
{
        return igrndtlreturnRepository.GetList(x=> x.GRNNo == "GRN00022" && 
                                                x.ProductCode == "D/F/HL/DM/0003/C/002")
            .Select(y => new GRNDtlReturnModel
            {
                GRNNo = y.GRNNo,

                totalQuantity = context.GRNDtlReturns.
                                Where(t=> t.GRNNo==y.GRNNo).Sum(p => p.ReturnQuantity)

            }).ToList();
}
Comments