Entity-framework code is slow when using Include() many times

前端 未结 3 1839
孤城傲影
孤城傲影 2020-11-29 01:59

I have been debugging some slow code and it seems that the culprit is the EF code posted below. It takes 4-5 seconds when the query is evaluated at a later stage. I\'m tryin

3条回答
  •  隐瞒了意图╮
    2020-11-29 02:44

    I've got a similar issue with a query that had 15+ "Include" statements and generated a 2M+ rows result in 7 minutes.

    The solution that worked for me was:

    1. Disabled lazy loading
    2. Disabled auto detect changes
    3. Split the big query in small chunks

    A sample can be found below:

    public IQueryable PerformQuery(int id) 
    {
     ctx.Configuration.LazyLoadingEnabled = false;
     ctx.Configuration.AutoDetectChangesEnabled = false;
    
     IQueryable customObjectQueryable = ctx.CustomObjects.Where(x => x.Id == id);
    
     var selectQuery = customObjectQueryable.Select(x => x.YourObject)
                                                      .Include(c => c.YourFirstCollection)
                                                      .Include(c => c.YourFirstCollection.OtherCollection)
                                                      .Include(c => c.YourSecondCollection);
    
     var otherObjects = customObjectQueryable.SelectMany(x => x.OtherObjects);
    
     selectQuery.FirstOrDefault();
     otherObjects.ToList();
    
     return customObjectQueryable;
     }
    

    IQueryable is needed in order to do all the filtering at the server side. IEnumerable would perform the filtering in memory and this is a very time consuming process. Entity Framework will fix up any associations in memory.

提交回复
热议问题