Entity Framework dispose context after Load Method

Indudhar Gowda 426 Reputation points
2022-05-05T14:02:09.797+00:00

Entity Framework dispose context after Load Method

this.Context.Recognitions.Where(rec => reportableResultIds.Contains(rec.ReportableResultId)).Load();

I want to Dispose the Context which is Eagerly Loaded on Method End and
During the Begging of the Method need to set the context again.

 public ReportableResultsRepository(
            IMemberUpdater memberUpdater,
            IReportableResultQueryGenerator queryGenerator,
            IDbContextPool contextPool,
            IConfigurationProvider configurationProvider)
        {
            this.memberUpdater = memberUpdater;
            this.queryGenerator = queryGenerator;
            this.contextPool = contextPool;
            this.configurationProvider = configurationProvider;
        }

   private IResultRepositoryDbContext Context
        {
            get
            {
                return this.contextPool.CurrentContext;
            }
        }

  unityContainer.RegisterType<IDbContextPool, DbContextPool>(new HierarchicalLifetimeManager());
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,374 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,713 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 26,201 Reputation points
    2022-05-07T11:56:31.287+00:00

    Need to optimize this line of code...Recognitions table has 6500000 Records...

    I suspect dropping the current design and moving to a standard load process is the best approach. Unfortunately, you continue to post questions as if the community can see your source code and we understand the design intent.

    The Contains method generates an IN clause which is ok for small lists. For large lists a join with proper indexes is far more performant.

    If the list of reportableResultIds are coming from an external source then load the reportableResultIds in to a table.

    If the reportableResultIds are coming from the database that contains the Recognitions table then use standard SQL constructs not LINQ. Keep in mind, if the reportableResultIds are coming from the database that contains the Recognitions table that means the reportableResultIds are copied from SQL to the client application and back to SQL with an IN clause. Plus the resulting SQL generated by LINQ is not optimal. This design wastes bandwidth and clock cycles.

    Basically, I'm recommending that you design a SQL solution rather than LINQ.