首页 > 解决方案 > 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);
            }

标签: c#entity-frameworklinq-to-sqlquery-optimization

解决方案


可能有一种方法可以提高性能,但不会通过切换SelectWhere(正如评论中提到的 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);

推荐阅读