Phidiax Tech Blog

Adventures in custom software and technology implementation.

SQL Azure: DataContext Error : The context cannot be used while the model is being created

I recently came across the titular error while updating an application using a DataContext to access a SQL Azure database when attempting to convert the DbSet to a list of objects. Because I was using a ToList() on the actual DbSet object on the context, it obscured the error away under an Argument Null Exception saying that the entitySet was null. If you review the exception of directly accessing the DbSet instead, you can see the full error message:

The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.

This error message directly covers what is most commonly expressed online as a cause of this error:

  1. Context is being used inside the initialize method of OnModelCreating (or being used while that method is executing)
  2. Multiple Threads are using the context
There are other potential causes for this error which are covered less commonly in the Google/Bing machine. I'm just trying to do my part to raise that to the top here! So if the above two items don't apply to your case, you should also look at your model classes: do they properly mirror the database table structure? If not, are you decorating those properties which are not in the database with the NotMapped Attribute to prevent EF from attempting to match those properties to a field in the database?

Hopefully this can prevent someone else out there from banging their head against their desk with this error after updating their database and/or EF model. 


Privacy Policy  |  Contact  |  Careers

2009-2017 Phidiax, LLC - All Rights Reserved