c# - EntityFremework:可以在哪里优化这个之前的选择吗?
问题描述
我正在尝试在此查询上获得性能,并且我想知道在 Where() 之前调用 Select() 是否可以进行一些改进:
public async Task<List<PostValues>> GetValuesToTheDashboard(DataFilter filter, CancellationToken cancellationToken) {
long startTimestanp = Helpers.UnixTimeNow(filter.StartDate);
long endTimestanp = Helpers.UnixTimeNow(filter.EndDate);
return await
_context.CatchDetails.Where(
x => x.Monitoring.Client.Id == filter.CustomerId && x.Data.published >= startTimestanp
&& x.Data.published <= endTimestanp
&& ((filter.Sentiment == Sentiments.ALL) || x.Sentiment_enum == filter.Sentiment)
&& (filter.MonitoringId == 0 || x.Monitoring.id == filter.MonitoringId)
&& (filter.KeywordId == 0 || x.Keyword.Id == filter.KeywordId)
&& (filter.MotiveId == 0 || x.Motive.Id == filter.MotiveId)
&& (filter.SocialNetwork.Count == 0 || filter.SocialNetwork.Any(s => x.Data.social_media == s))
&& (filter.Busca == "" || x.Data.content_snippet.Contains(filter.Busca))
&& (filter.Gender.Count == 0 || filter.Gender.Any(g => x.Data.extra_author_attributes.gender_enum == g)))
.Select(s => new PostValues() {
CatchDetailsId=s.Id,
Monitoring=s.Monitoring.name,
Keyword=s.Keyword.Text,
Motive=s.Motive.Name,
Sentiment=s.Sentiment_enum,
Gender=s.Data.extra_author_attributes.gender_enum,
SocialMedia=s.Data.social_media,
Country=s.Data.extra_author_attributes.world_data.country_code,
State=s.Data.extra_author_attributes.world_data.region,
Published=s.Data.published
}).ToListAsync(cancellationToken);
}
解决方案
可能有一种方法可以提高性能,但不会通过切换Select
和Where
(正如评论中提到的 Chetan )。
您可以按顺序构建查询,并基于过滤器最终获得更简单的查询。这将是这样的:
var query = _context.CatchDetails.Where(
x => x.Monitoring.Client.Id == filter.CustomerId && x.Data.published >= startTimestanp
&& x.Data.published <= endTimestanp);
if (filter.Sentiment != Sentiments.ALL)
{
query = query.Where(x => x.Sentiment_enum == filter.Sentiment);
}
if (filter.MonitoringId != 0)
{
query = query.Where(x => x.Monitoring.id == filter.MonitoringId);
}
[...]
return await
query.Select(s => new PostValues() {
[...]
}).ToListAsync(cancellationToken);
推荐阅读
- mercurial - 汞进来有什么意义?
- javascript - 避免 JavaScript 函数中的重复代码
- git - 在 Github 上合并拉取请求后,本地“未合并的提交被丢弃”
- compilation - 在 FreeBSD 下链接端口库
- html - 想要重复一个 div 来填充它的父级
- javascript - Google Drive API:通过 Multipart API 上传二进制文件的正确方法
- javascript - 如何在 Photoshop 中展平数组?
- powershell - 使用 Azure Powershell Runbook 将 Csv 文件转换为 Azure 数据湖存储上的 Xml
- javascript - 在 react 中使用 setState 将预定义的对象推送到数组中
- r - 使用 SparkR 离散化变量