我想获取一份报告的汇总数据,该报告显示实体框架语法中每个决策的总数和供应商数量。我的结果需要包括金额总和和每个决策的供应商总数。
我有一个供应商表,其中包含以下列:
SupplierNo | Decision | DecisionIssuedOn | Amount | SupplierGroup | SubSupplier
在特定时间段内获取上述数据的原始SQL查询是:
SELECT S.Decision, SUM(S.Amount) AS TotalAmount, COUNT(DISTINCT S.SupplierNo) AS SupplierCount
FROM (SELECT * FROM Indentors WHERE Indentors.DecisionIssuedOn BETWEEN '2018-01-01' AND '2018-12-31') S
GROUP BY S.Decision
哪个给出的数据为:
SupplierCount | Amount
-----------------------
Approved 20 | 5000
Rejected 11 | 3000
In-Process 5 | 1500
现在从前端开始,条件参数可以是给定选项池(下拉列表)中的任何内容,这些选项在被选中时会在像这样的exixing查询中添加where子句
WHERE Decision = 'Approved' AND SupplierGroup ='ABC' AND SubSupplier ='zxc'
问题是我很难使用Entity Framework lambda表达式而不是原始SQL来获得所需的结果。
我到目前为止所做的:
我检查了从fornt-end到Options where的可用性,以构建where子句为:
IQueryable<Supplier> suppliers = this.db.suppliers.OrderByDescending(i => i.Id);
if (string.IsNullOrEmpty(selectedSupplierGroup) == false)
{
suppliers = suppliers.Where(i => i.SupplierGroup == selectedSupplierGroup);
}
if (string.IsNullOrEmpty(selectedSubSupplier) == false)
{
suppliers = suppliers.Where(i => i.SubSupplier == selectedSubSupplier);
}
if (string.IsNullOrEmpty(selectedDecision) == false)
{
suppliers = suppliers.Where(i => i.Decision == selectedDecision);
}
if (selectedDecisionIssuedOn.HasValue)
{
suppliers = suppliers.Where(i => i.DecisionIssuedOn >= selectedDecisionIssuedOn);
}
var result = suppliers
.GroupBy(i => i.Decision)
.Select(i => i.SupplierNo).Distinct().Count(); // Gives me error
错误是:
IGrouping不包含SupplierNo的定义,也没有扩展方法等等……
但是在那之后,我无法获取数据,因为原始查询(如上所述)会帮助我。谢谢
答案 0 :(得分:1)
这应该为您提供与SQL查询类似的结果。试试看,看看你如何过:
var results = suppliers
.Where(i => i.DecisionIssuedOn >= selectedDecisionIssuedOn)
.GroupBy(i => i.Decision)
.Select(group => new
{
Decision = group.Key,
TotalAmount = group.Sum(g => g.Amount),
SupplierCount = group.Select(i => i.SupplierNo).Distinct().Count()
});