[英]How to get sum of two column values from SQL table using Entity Framework?
I have a table name GRNDtlReturn
in above mention screenshot. 我在上面提到的屏幕截图中有一个表名GRNDtlReturn
。 I want to get the sum of ReturnQuantity
of first and third rows in table. 我想获取表中第一行和第三行的ReturnQuantity
之和。 I have written some code, but it returns the sum of full ReturnQuantity
column. 我已经写了一些代码,但是它返回了完整的ReturnQuantity
列的总和。 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();
}
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();
}
I assume that igrndtlreturnRepository.GetList(x => x.GRNNo == grnno && x.ProductCode == productcode)
returns an IQueryable<GRNDtlReturn>
according to the filter expression. 我假设igrndtlreturnRepository.GetList(x => x.GRNNo == grnno && x.ProductCode == productcode)
根据过滤器表达式返回IQueryable<GRNDtlReturn>
。
Case 1: Get a single result for GRNNo = "GRN00022"
and ProductCode = "D/F/HL/DM/0003/C/002"
情况1:获得GRNNo = "GRN00022"
和ProductCode = "D/F/HL/DM/0003/C/002"
的单个结果
In this case, the result of GetList
is already limited to the relevant entries and there should be a single result GRNDtlReturnModel
if any row matches the criteria. 在这种情况下, GetList
的结果已经限于相关条目,并且如果有任何行符合条件,则应该有一个单一的GRNDtlReturnModel
结果。
GRNDtlReturnModel result = igrndtlreturnRepository.GetList(x => x.GRNNo == "GRN00022" && x.ProductCode == "D/F/HL/DM/0003/C/002")
.GroupBy(x => x.GRNNo, (k, v) => new GRNDtlReturnModel { GRNNo = k, totalQuantity = v.Sum(q => q.ReturnQuantity) })
.FirstOrDefault();
Case 2: Get the group-sum for all matching combinations of GRNNo
and ProductCode
情况2:获取GRNNo
和ProductCode
所有匹配组合的GRNNo
和
In this case, the grouping expression needs to contain all relevant group keys, the calculation of sum stays the same. 在这种情况下,分组表达式需要包含所有相关的组密钥,总和的计算保持不变。
IList<GRNDtlReturnModel> result = igrndtlreturnRepository.GetList(x => true)
.GroupBy(x => new { x.GRNNo, x.ProductCode }, (k, v) => new GRNDtlReturnModel { GRNNo = k.GRNNo, totalQuantity = v.Sum(q => q.ReturnQuantity) })
.ToList();
This should be more efficient than a nested access to context.GRNDtlReturns
. 这比嵌套访问context.GRNDtlReturns
更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.