加快此 linq 查询的查询执行时间

问题描述 投票:0回答:1

我有一个执行以下操作的查询:

  • 从数据库中提取孩子
  • 过滤此子项以获取无法加入 availableItems 查询的子项(不在 availableItems 表中)
  • 过滤可用项目并将其检索到内存中
  • 与 availablesItems 和 ChildrensWithoutItems 执行左连接,然后使用左连接结果执行笛卡尔积
  • 执行与 availableItems 和 Childrens 的内部连接

有什么技巧可以加快执行时间吗?

var authorizeType = new List<TreeNodeType> {
        TreeNodeType.Equipment,
        TreeNodeType.StructuredArea
    };

        
var childrens = await (from n in _db.TreeNodes.Where(n => n.TreeNodeId == treeNodeParentId)
                       from path in _db.TreeNodes.Where(p => (EF.Functions.Like(p.Path, n.Path + "%")) && authorizeType.Contains(p.Type))
                       select new
                       {
                           path.Name,
                           path.FullName,
                           path.Type,
                           path.HorusId,
                       }).ToListAsync();

var childrensWithoutItems = childrens.Where(i => !_db.AvailableItems.Select(d => d.HorusId).Contains(i.HorusId));

var availableitems = await _db.AvailableItems.Where(x => x.HorusId == null || childrens.Select(d => d.HorusId).Contains(x.HorusId.Value)).ToListAsync();

//without items
var withoutItems =
     (from c in childrensWithoutItems
      from co in availableitems
      join tree in childrens on co.HorusId equals tree.HorusId into left
      from le in left.DefaultIfEmpty()
      join i in items on co.ItemIdentifier equals i.Identifier
      where le == null
      select new OrganizationItemDetail {
          OrganizationPath = c.FullName,
          OrganizationChildName = c.Name,
          OrganizationType = c.Type,
          Name = i.Name,
          Packaging = i.Packaging.ToString(),
          ShortName = i.ShortName,
          Type = i.Type.ToString(),
          UnitValue = i.UnitValue,
      });


//with items 
var withItems = (from co in availableitems
                              join tree in childrens on co.HorusId equals tree.HorusId
                              join i in items on co.ItemIdentifier equals i.Identifier
                              select new OrganizationItemDetail {
                                  OrganizationPath = tree.FullName,
                                  OrganizationChildName = tree.Name,
                                  OrganizationType = tree.Type,
                                  Name = i.Name,
                                  Packaging = i.Packaging.ToString(),
                                  ShortName = i.ShortName,
                                  Type = i.Type.ToString(),
                                  UnitValue = i.UnitValue,
                              });


var un = withoutItems.Concat(withItems);
c# .net performance linq
1个回答
0
投票

尝试添加 .AsNoTracking() 作为开始。

© www.soinside.com 2019 - 2024. All rights reserved.