如何在单个select语句中执行此操作?
var data = new CampaignData()
{
TotalPost = await context.Campaigns.SumAsync(c => c.Posts),
AveragePost = await context.Campaigns.AverageAsync(c => c.Posts),
TotalImpression = await context.Campaigns.SumAsync(c => c.Impressions),
AverageImpressions = await context.Campaigns.AverageAsync(c => c.Impressions),
};
答案 0 :(得分:6)
您可以按常数分组,以便获得总和和平均值。然后使用SingleAsync
获取单个结果。
var data = await (from compaign in context.Compaigns
group compaign by 1 into grp
select new CampaignData()
{
TotalPost = grp.Sum(cc => cc.Posts),
AveragePost = grp.Average(c => c.Posts),
TotalImpression = grp.Sum(c => c.Impressions),
AverageImpressions = grp.Average(c => c.Impressions),
}).SingleAsync();
另一种选择是实际让异步数据库调用并行运行
var totalPostTask = context.Campaigns.SumAsync(c => c.Posts);
var averagePostTask = context.Campaigns.AverageAsync(c => c.Posts);
var totalImpressionTask = context.Campaigns.SumAsync(c => c.Impressions);
var averageImpressionsTask = context.Campaigns.AverageAsync(c => c.Impressions);
await Task.WhenAll(
totalPostTask,
averagePostTask,
totalImpressionTask,
averageImpressionsTask);
var data = new CampaignData()
{
TotalPost = totalPostTask.Result,
AveragePost = averagePostTask.Result,
TotalImpression = totalImpressionTask.Result,
AverageImpressions = averageImpressionsTask.Result,
};
如果我不得不猜测我说单个数据库调用会表现更好,但你总是可以测试两个选项,看看哪个更好。