Entity Framework Initialization Is Slow -- What How to Do to Bootstrap It Faster

Entity framework very slow to load for first time

Could be EF, but just as likely could be that your app pool is getting recycled on IIS or a combination.

If there are going to be slow periods of usage on your website, and you want each page to load fast for a visitor that happens along, in the past I have setup a timed job to hit my website at specific intervals (about 5 minutes worked for me), and that made sure that it was always ready to go when a visitor came along.

Very easy to do if you have access to a task scheduler.

Any way to speed up CreateIfNotExists in Entity Framework?

This works fine but is dog slow.

Yes. The point is to use the real database only for integration tests which don't have to be executed so often and the whole set of integration tests is usually executed only on build server.

It can take up to 15 seconds to create the database on the first call

This is because of slow initialization of EF when unit testing (you can try to switch to x86). The time is also consumed by view generation. Views can be pre-generated which is usually done to reduce startup and initialization of the real system but in case of speeding up unit tests using view pre-generation will not help too much because you will just move the time from test to build.

I'm willing to go around EF to do this if that helps, but I would like to keep my database build in code and not go back to a SQL

Going around would just mean using plain old SQL script. The additional time needed for this operation is may be spent in generating that SQL. I think the SQL is not cached because normal application execution normally doesn't need it more than once but you can ask EF to give you at lest the most important part of that SQL, cache it somewhere and execute it yourselves every time you need it. EF is able to give you SQL for tables and constraints:

var dbSql = ((IObjectContextAdapter) context).ObjectContext.CreateDatabaseScript();

You just need to have your own small SQL to create database and use them together. Even something like following script should be enough:

CREATE DATABASE YourDatabaseName

USE YourDatabaseName

You must also turn off database generation in code first to make this work and to take control over the process:

Database.SetInitializer<YourContextType>(null);

When executing database creation SQL you will need separate connection string pointing to Master database.



Related Topics



Leave a reply



Submit