.netentity-frameworkapp-configtypeinitializationexception

EntityFramework Type Initialization Exception


This is a possible duplicate of these question below. However using the answers provided there I have still failed to fix the issue.

Question

My issue seems almost identical to this. I have a class library to store two .edmx files which is then references by two other class libraries. I want to test the database queries in a unit testing project but always receive the following error.

"The type initializer threw an exception...System.TypeInitializationException: No connection string named 'MyModel' could be found in the application config file" where 'MyModel' obviously refers to either of the two .edmx models.

Based on the previous answers to this topic I have copied the App.config file from my EntityFramework project to both class library projects and indeed the unit test project but still receive the error.

Any help would be appreciated. If it makes any difference I am using VS2012 and .Net 4.5.

Thanks Richard


Solution

  • Putting the app.config in a class library won't fix the problem, since the class libraries aren't the start-up application, they're just being referenced and therefore the app.config is never actually read from. When testing, you should pass the connection string directly to your DbContext when it's being constructed.