Using Enity Framework 6.1 and initial query VERY slow.

Gary Paquette 0 Reputation points
2024-08-07T19:04:09.36+00:00

When performing the initial query using EF, it can take up to 9 mins. Though if you rerun it again and again it takes seconds. If I capture the query from the profiler, it always runs in seconds.

If I wait about 10 / 15 mins the slow initial process starts over.

Any way of dealing with this or a setting?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
751 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,921 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Hongrui Yu-MSFT 2,465 Reputation points Microsoft Vendor
    2024-08-08T08:13:00.08+00:00

    Hi,@Gary Paquette. Welcome to Microsoft Q&A. Optimization

    1.For only part of the query available use AsNoTracking().

    
    var items = EFDbContext.MyDbSet.AsNoTracking().ToList();
    
    

     

    2.Use Ngen to install and generate a local image of EF.

    a. Open a cmd window.

    b. Switch to the bin directory of the program, such as: cd d:\website\bin.

    c. Run the ngen command.

    For 32 bit run:

    
    %WINDIR%\Microsoft.NET\Framework\v4.0.30319\ngen install EntityFramework.SqlServer.dll
    
    

     

    For 64 bit run:

    
    %WINDIR%\Microsoft.NET\Framework64\v4.0.30319\ngen install EntityFramework.SqlServer.dll
    
    

     

    3.Disabling the first EF query on the table __MigrationHistory(For Code first projects).

    Add code

    
    Database.SetInitializer<EFDbContext>(null);
    
    

    EFDbContext is the EF context class of my project. You need to replace it with your own EF context class according to your project.

     

    4.EF Pre-Generated Mapping Views.

    Add code

    
    using (var dbcontext = new EFDbContext())
    
    {
    
    var objectContext = ((IObjectContextAdapter)dbcontext).ObjectContext;
    
    var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace);
    
    mappingCollection.GenerateViews(new List<EdmSchemaError>());
    
    }
    
    

    5.If access becomes slow after a period of time, you could set the "idle timeout" of the application to make it longer. Or you could create a scheduled task to use EF regularly.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.