DBContext slow when initially building

.net-core c# entity-framework-core


We are currently using EF Core and have over 250 tables. Lately I have found out about warming up dbContexts and them going cold. So have learnt alot, possibly stuff I should really have known about. So it turns out that multiple dbContexts in my case is a good approach. So I have managed to create a bounded dbContext for a domain within out architecture.

We have managed to get the initial dbContext construction down to about 18s. This is good from what we had so we are pleased. So in the dbContext I have created there is an OnConfiguring method which is almost instant. Then there is an 8 secs gap and then we hit the OnModelCreating method, which takes 8secs from beginning to end.

So I was wondering what is going on exactly between the completion of the OnConfiguring method and the start of the OnModelCreating method. This 8 secs gap is now where I need to work to reduce. Is this the security and login to SQLServer bit which is taking the time.

Does anyone know whether I could invoke this part somewhere else, possibly within the startup config. So that we can seperate this section from the initial warming up of the dbContext. At present it is all done when I actually do a query.

Update 13/04/2018

So I have been looking into this issue and have worked out where the 8 secs are coming from. The modelBuilder builds a snapshot of the database in it's entirety and then from that we then build our bounded dbContexts. So whether I create a bounded db context with 1 table or 40, the modelBuilder class still uses the 8 secs to get everything from the whole database. So the full 240 tables.

Does anyone know of a way we can prevent this modelBuilder from grabbing the complete database, when we only need a few of the tables. So we can then infer our dbContext from that.

4/13/2018 2:27:20 PM

Accepted Answer

So to resolve this issue I had to revert partially to using data-annotations. Where I have multiple dbContexts I initially used the FluentAPI ignore property. Something like this...

modelBuilder.Entity<User>().Ignore(p => p.Facility);

By changing it and using the [NotMapped] attribute within the model itself I was able to ensure that the dbContext warming is really kept to a bare minimum.

public ICollection<Users> Users{ get; set; }

It creates extra work but does resolve this particular issue. So overall if you don't want a delay when initially warming up a large dbContext then use the data-annotations approach where possible.

6/28/2018 2:27:48 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow