Preloading a context before using it

It's hard to explain, so bear with me.

I have an Entity framework context that is being used by a view model. Basically, it is a search box that has a service that uses context to run queries based on search criteria.

The problem is when the first search is done , then it DbContext

starts and searches the database to generate entities and relationships. (At least that's what I think is going on)

This is shown below:

Initial search

The first lookup takes a few seconds as the Entity Framework does it. After performing the first search, all other searches are performed almost instantly. This is just the first search and it takes a long time.

Search results

Now for my question.

Is it possible to force the DbContext

relationship to load and generally do it (asynchronously) before any action is taken in the context? those. request.

Ideally, your first search should be as fast as other searches.

+3


source to share


2 answers


Yes, just ask for objects, but don't do anything with them. dbContext

then caches the results.



+1


source


What takes a long time on first use depends on the size of your db schema (EF virtual tables creation) and is executed once at runtime on first instance.

Just initialize the context on another thread at startup and make any request on it and this attack will be performed asynchronously.



Don't try to keep a link to this context, contexts are cheap to create and they are meant to be short lived, which is expensive, this is only the first time you create one in your process.

If slowdown is an issue even asynchronously, you can make EF do the job at compile time, but it's somewhat involved

+1


source







All Articles