AllmanTool
AllmanTool

Reputation: 1554

Why is the process of obtaining ObjectContext from dbContext so slow?

I use in my work Entity Framework Code first (6.2). One of the biggest problem with such approach is slow performance at first query. I use InteractiveViews nuget package to workaround this issue, but unfortunately, it doesn't give expected productivity growth.

When I was experimenting with source code, i noticed that

**( dbContext as IObjectContextAdapter).ObjectContext**

took i very long time ( 8 sec. in my case).

Q: What is the reason for the such big delay? Is it normal or it possible somehow to solve?

Upvotes: 2

Views: 719

Answers (1)

Jonathan Magnan
Jonathan Magnan

Reputation: 11347

new DbContext

Creating a new context such as var ctx = new DbContext() doesn't make the model to be compiled or do any database verification with the Migration History table.

It could take 500ms because it JIT compiles some method within Entity Framework or another third library that you may call in your constructors.

It's hard to know why it takes 500ms because they might have several reasons.

(dbContext as IObjectContextAdapter).ObjectContext

Doing it mean the OnModelCreating method will be invoked, and the model will be compiled for the first time. Some query will be executed on the database as well.

The best way to find out is making a simple test, adding some break point, and enabling SQL Profiler to see it by yourself:

var ctx = new CurrentContext1();
var objectContext = (ctx as IObjectContextAdapter).ObjectContext;

You will suffer from the same performance problem as people usually report when they ask Why Entity Framework First Load is Slow

Upvotes: 3

Related Questions