[asp.net] The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I'm working with EF5 in a MVC 4 aspnet website. Locally, everything works just fine, but when I publish it to the IIS and try to enter, I get the error

"The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception."

Detailed exception

An error occurred creating the configuration section handler for entityFramework: Configuration for DbContext type 'GdpSoftware.Server.Data.GdpSoftwareDbContext, GdpSoftware.Server.Data' is specified multiple times in the application configuration. Each context can only be configured once. (E:\App\web.config line 104)

I checked previous question in StackOverflow, and I already uninstalled and reinstalled through Nuget EntityFramework and checked that each reference to it in each project is EF5. I also checked that the selected framework in each project is 4.5.

Any idea, What might be causing the issue? Thanks! Guillermo.

web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
  <connectionStrings>
    <add name="GdpSoftwareConnectionString" connectionString="Persist Security Info=False;User ID=user;Password=password;Initial Catalog=databasename;Data Source=server" providerName="System.Data.SqlClient" />
    <add name="GdpSoftware.Server.Data.GdpSoftwareDbContext" connectionString="GdpSoftware.Server.Data.GdpSoftwareDbContext_ConnectionString" providerName="System.Data.SqlClient"/>
    <add name="GdpSoftware.Server.Ui.Web.Models.UsersContext" connectionString="GdpSoftware.Server.Ui.Web.Models.UsersContext_ConnectionString" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <!-- BEGIN - TO SEE THE ERRORS ON THE DEPLOYMENT-->
    <customErrors mode="Off" />
    <!-- END - TO SEE THE ERRORS ON THE DEPLOYMENT-->
  </system.web>
  <system.webServer>
    <!-- BEGIN - TO SEE THE ERRORS ON THE DEPLOYMENT-->
    <httpErrors errorMode="Detailed" />
    <asp scriptErrorSentToBrowser="true" />
    <!-- END - TO SEE THE ERRORS ON THE DEPLOYMENT-->
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <staticContent>
      <mimeMap fileExtension=".mustache" mimeType="text/plain" />
    </staticContent>
    <security>
      <requestFiltering>
        <fileExtensions>
          <add fileExtension=".mustache" allowed="true" />
        </fileExtensions>
      </requestFiltering>
    </security>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Castle.Windsor" publicKeyToken="407dd0808d44fbdc" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.2.0.0" newVersion="3.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="4.5.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Host.SystemWeb" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.0.0.0" newVersion="1.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Castle.Core" publicKeyToken="407dd0808d44fbdc" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.2.0.0" newVersion="3.2.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <contexts>
      <context type="GdpSoftware.Server.Data.GdpSoftwareDbContext, GdpSoftware.Server.Data" disableDatabaseInitialization="true">
        <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[GdpSoftware.Server.Data.GdpSoftwareDbContext, GdpSoftware.Server.Data], [GdpSoftware.Server.Data.Migrations.Configuration, GdpSoftware.Server.Data]], EntityFramework" />
      </context>
    </contexts>
  </entityFramework>
</configuration>

The answer is


Change this part in your Web.config, according to the below code.(try this, it works to me.)

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=.; Integrated Security=True; MultipleActiveResultSets=True" />   
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>

actual error thrown Message=Unrecognized element 'providers' in web.config so from the web.config file remove the providers section


I had same problem. After one day, I got it.

Problem was from adding two smtp tags in mailSettings under <system.net>.


Check the C-drive inside C:\inetpub\wwwroot and remove all unnecessary folders from it, else remove unnecessary host files or folders from IIS.


If you are maintaining one more cinfiguration file for app.config , Don't include any key in parent page.

Parent Page : app.config

<appSettings configSource="appSettings.config">
    <add key="ClientSettings" value="venice" /> <!-- Don't add Key Here -->
</appSettings>

Child Page : appSettings.config

<appSettings>
  <add key="ClientSettings" value="venice"/> <!-- add Here -->
</appSettings>

Old question but it just happened to me for different reasons mentioned in the other answers, so I thought I'd share my findings.

In my case, the problem was how I defined my connection string entry in the app.config. I edited it directly in Notepad++ and I must have hit a shortcut, and minimized the entire string which I didn't spot, and started to get this error. This is how I was defined it:

<add name="MyDb" connectionstring="data source=MyServer;
 initial catalog=MyDatabase;integrated security=true" 
 providername="System.Data.SqlClient" />

The second I changed the following parameters

connectionstring to connectionString

and

providername to providerName

Note: The problem was highlighted immediately In Visual Studio but clearly this isn't ideal if you're on a client site!


I had multiple providers specified in my web.config.

 <providers>
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
    </providers>

I simply removed one of those and it worked.

I am using MySQL though, not TSQL


Do the following in the App.config file,

  1. Put the connectionStrings element is after the configSections element.
  2. Put the startup element after the connectionStrings element.
<?xml version="1.0" encoding="utf-8"?>
 <configuration>
   <configSections>
         <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
   </configSections>
   <connectionStrings>
         <add name="SchedulingContext" connectionString="Data Source=XXX\SQL2008R2DEV;Initial Catalog=YYY;Persist Security Info=True;User ID=sa;Password=XXX"   providerName="System.Data.SqlClient"/>
   </connectionStrings>
   <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>       
 </configuration>

I ran into this issue when I forgot to set my Connections.config file to "copy always"

BareMessage = "Unable to open configSource file 'Connections.config'."


in my case adding <clear /> just after <connectionStrings> worked like charm


I had the duplicate definition of connection string in my Project Cms.And the Context class is named:CmsContext

In my case, the problem was solved, as I changed the connectionsting in Web.config as follow:in first one name is CmsContext and it's related to main project .in second one name is DefaultConnection and it's related to Identity

<add name="CmsContext" providerName="System.Data.SqlClient" connectionString="Data Source=DESKTOP-2NQSP1P\SQLEXPRESS;  Initial Catalog=CmsDB;Integrated Security=True;" />
</connectionStrings>

I have broken my head over this issue, and finally here's what worked for me:-

Step1 : Uninstall Entity framework using Nuget package manager

Step2: Delete Entityframework element from App.config

Step3: Reinstall desired version of Entity Framework.

Step4: delete Migrations table and Migrations folder.

Step5: Enable Migrations and Add Migration and Update database


I Found that removing the references to Entity Framework and installing the latest version of Entity Framework from NuGet fixed the issue. It recreates all the required entries for you during install.


Search in your web.config or App.Config if you have some tags that are not used in your project or you don't have in your references.


The general issue is just any issue involving Machine/Web/App configs.

I had the same connection strings in Machine.Config as in my App.Config so I put before my first connection string in my App.Config


I solved this problem removing DbproviderFactory in the section system.data of the file machine.config, there was some dirty data when I installed fbclient.dll.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config

  <system.data>
    <!-- <DbProviderFactories><add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient, Version=4.10.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c"/><add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient, Version=6.4.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c"/> -->
  </system.data>

I had this error today on a nested MVC application running as virtual folder in onother MVC application. In my case the InnerException was more informative than the main one. It was stating:

- The entry 'DbContextMain' has already been added. (C:\inetpub\...\web.config line x)

After fixing the duplicate connection strings in the nested apps everything worked fine.


If you use ASP.NET and IISExpress go to "C:\Users\\Documents\IISExpress\config\applicationhost.config", search for your Project and look if you have a faulty virtualDirectory entry.


I think the problem is from this line:

<context type="GdpSoftware.Server.Data.GdpSoftwareDbContext, GdpSoftware.Server.Data" disableDatabaseInitialization="true">

I don't know why you are using this approach and how it works...

Maybe it's better to try to get it out from web.config and go another way


This weird error happens, when you play around with different versions of EntityFramework versions in Nuget Packages like I did.

First, Uninstall your Entity Framework DLL from NuGet packages and then Clean up app.config. By removing the entry from configSections and entity framework element.

Next, install the desired version. This should fix the problem.


in my case

<section name="entityFramework"

must be updated from version 4 to 6. I mean a project was updated EntityFramework from 4 to 6 but web.config was not updated.


I had the duplicit definition of connection string in my WCF service. I was able to debug the service and to see the inner error message (not displayed by default):

ConfigurationErrorsException: The entry 'xxxEntities' has 
already been added. (C:\Users\WcfService\web.config line 35). 

which was after web.config transformation (note duplicit values)

<connectionStrings>
    <add name="xxxEntities" connectionString="metadata=res://*/ ...
    <add name="xxxEntities" connectionString="metadata=res://*/ ...

Hence removing unwanted connection string solved my problem.


In connection string, the first string is the base in web.config

SchedulingContext is the base parameter of Entity file.

<connectionStrings>
     <add name="SchedulingContext" connectionString="Data Source=XXX\SQL2008R2DEV;Initial Catalog=YYY;Persist Security Info=True;User ID=sa;Password=XXX"   providerName="System.Data.SqlClient"/>


I also faced the same issue, however in my case my solution has a console application and EF class library which mainly interacts with database. I removed Config settings related to EF from the Console Application Config. I maintained the following configuration settings in EF class library i.e only at one place.

This worked for me.


<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.2.61023.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

<add name="EntityModel" connectionString="Server=Localhost\SQLEXPRESS;Database=SampleEntities;Trusted_Connection=True;" providerName="System.Data.EntityClient" />



I faced similar issue and changing defaultConnectionFactory to be SqlConnectionFactory helped me solve it.


Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?

Examples related to entity-framework-5

Entity Framework Join 3 Tables The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 EF LINQ include multiple and nested entities Entity Framework 5 Updating a Record Non-static method requires a target How do I enable EF migrations for multiple contexts to separate databases? After updating Entity Framework model, Visual Studio does not see changes Entity Framework Migrations renaming tables and columns