Managing EntityConnection lifetime

There have been many question on managing EntityContext lifetime,

e.g. Instantiating a context in LINQ to Entities

I’ve come to the conclusion that the entity context should be considered a unit-of-work and therefore not reused. Great.

But while doing some research for speeding up my database access, I ran into this blog post…

Improving Entity Framework Performance

The post argues that EFs poor performance compared to other frameworks is often due to the EntityConnection object being created each time a new EntityContext object is needed.

To test this I manually created a static EntityConnection in Global.asax.cs Application_Start().

I then converted all my context using statements to

using( MyObjContext currContext = new MyObjeContext(globalStaticEFConnection)

This seems to have sped things up a bit without any errors so far as far as I can tell.

But is this safe?

Does using a applicationwide static EntityConnection introduce race conditions?

Best regards,


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

EntityConnection is documented to be not thread-safe. I think you could pool them, but you cannot use a single, static connection for a Web application, as there will be many threads involved.

Method 2

  • If your EF context is Application-wide, consider that user A has made changes (not committed) & user B has committed his changes, all changes will get committed to the database since both user A & B use the same instance
  • In my project, I did a per WebRequest intance of the EF context – ie. a context object is static from start through end of a web request & all operations in that request work with the same EF context. This has significantly speeded up my processing without the problem mentioned above.

One way to implement this is to use a DI container (I am using Unity) to manage the lifetime of the EF context. The per web request lifetime manager is not given out of the box in Unity, but there are tons of articles out there which show how this can be done.


All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x