【问题标题】:Get Query optimization in ef-core and Linq在 ef-core 和 Linq 中获取查询优化
【发布时间】:2021-09-06 02:03:43
【问题描述】:

这个查询大约需要 5 分钟才能返回 60 条记录。

我可以做些什么来提高性能?

var values = await (from x in _context.things.DefaultIfEmpty()
                      let p = _context.MatchedThings.Where(a => a.Status == Status.Active)
                      .DefaultIfEmpty()
                      .AsNoTracking()
                      select new ThingReport
                      {
                          thing = x,
                          PreferredRate = x.Rate,
                          CreatedDate = x.CreatedDate,
                          IsMatched = (p == null ? false : p.Any(y =>
                          (y.MyThingId == x.Id || y.PairedThingId == x.Id)
                          && (y.MatchedThingStatus == MatchedThingStatus.Matched || y.MatchedThingStatus == MatchedThingStatus.Fulfilled || y.MatchedThingStatus == MatchedThingStatus.Processing
                          || y.MatchedThingStatus == MatchedThingStatus.Completed || y.MatchedThingStatus == MatchedThingStatus.Refunded)
                          )),
                          MatchedOrder = p
                      }).OrderByDescending(a => a.CreatedDate)
                      .ToListAsync();

【问题讨论】:

    标签: sql sql-server performance linq entity-framework-core


    【解决方案1】:

    尝试以下查询。我认为它应该工作得更快,否则您必须分析 SQL 执行计划以查找丢失的索引。

    var query =
        from x in _context.things
        from p in _context.MatchedThings
            .Where(p => p.Status == Status.Active)
            .Where(p => (p.MyThingId == x.Id || p.PairedThingId == x.Id)
                && (p.MatchedThingStatus == MatchedThingStatus.Matched || p.MatchedThingStatus == MatchedThingStatus.Fulfilled || p.MatchedThingStatus == MatchedThingStatus.Processing
                || p.MatchedThingStatus == MatchedThingStatus.Completed || p.MatchedThingStatus == MatchedThingStatus.Refunded)
            )
            .Take(1)
            .DefaultIfEmpty()
        select new ThingReport
        {
            thing = x,
            PreferredRate = x.Rate,
            CreatedDate = x.CreatedDate,
            IsMatched = p != null,
            MatchedOrder = p
        };
    
    var result = await query
        .OrderByDescending(a => a.CreatedDate)
        .ToListAsync();
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 2022-01-14
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 2020-01-25
      • 2021-02-22
      • 2021-01-30
      • 2019-03-27
      相关资源
      最近更新 更多