54

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>
Nico
  • 12,493
  • 5
  • 42
  • 62
polonskyg
  • 4,269
  • 9
  • 41
  • 93

28 Answers28

88

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>
Carrie Kendall
  • 11,124
  • 5
  • 61
  • 81
Diganta Kumar
  • 3,637
  • 3
  • 27
  • 29
  • 2
    Moving `startup` after the `connectionString` section did the trick for me. Thanks. – Erik Olson Sep 29 '14 at 21:55
  • i previously put my connection string at an arbitrary location so this resolved my issue. thanks! – Don Barry Nov 08 '14 at 07:46
  • You saved my day ! Step 2 did the work. Don't understand how changing sequence of startup can make the difference ! This is Microsoft, anything can be happen. – Altaf Patel Jul 06 '15 at 13:30
  • I had same problem, 2 day banging head against wall and moving connectionSrings outside configSections works. – Piotr M Mar 31 '17 at 22:07
  • Exact same problem here after adding log4net section to my app.config. Unfortunately no amount of reordering makes the error go away (yes, my log4net markup is valid, tested in a non-EF app to verify it) :-( – markaaronky Sep 29 '17 at 14:12
26

I needed to change by defaultConnectionFactory to be SqlConnectionFactory instead of the default

<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="<My Connection String>" />
    </parameters>
  </defaultConnectionFactory>
</entityFramework>

http://blogs.msdn.com/b/davidobando/archive/2012/08/14/changing-ef-s-default-provider-from-localdb-to-sql-server.aspx

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Brian
  • 1,845
  • 1
  • 22
  • 37
  • Thanks so much for pointing that out...I had been beating my brains out trying to figure out why EF code first was creating my db on localdb instead of in SQL Server like I had specified in my connectionString. – levininja Nov 05 '14 at 22:43
  • 2
    I had to do this, but also add the provider like this: ` ` as specified in [the documentation](http://msdn.microsoft.com/en-us/data/jj556606.aspx#Providers). – levininja Nov 05 '14 at 23:04
  • My problem was because of EntityFramework version upgrade. The config section must be checked if there is a version upgrade. :) – Davut Engin Jun 03 '20 at 13:23
6

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.

Ben Pretorius
  • 4,079
  • 4
  • 34
  • 28
5

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

Golden Griffin
  • 451
  • 1
  • 5
  • 9
  • Thank you very much for this. I always have a problem with EF installing different versions depending on which version of ASP.NET being used. As a result, I always end up installing if a few times to get it right. Clearing out the old rubbish in the web.config fixed this issue a treat, thanks. – Christopher Thomas May 23 '16 at 10:12
2

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

Luke
  • 22,826
  • 31
  • 110
  • 193
  • Mine had 3 providers. I removed 1 to fix that error. – Olorunfemi Davis Jan 13 '19 at 03:45
  • Along these lines, here's what I ran into: I left a copy of web.config in a sub-directory with a connection string name that was the same, ie, redundant with what I kept looking at in the correct directory! Deleted that web.config and this error went away. I should add: I only discovered this *after* I tweaked my error reporting method to dump the InnerExceptions. – Gary Huckabone Dec 22 '19 at 21:20
2

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 had a similar problem with my Test project code throwing an error and I was able to get it fixed by having the connection strings in my test project match up with the connections strings in my asp.net mvc project. – Nathan Prather Apr 02 '19 at 18:48
1

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'."

Matt Knight
  • 499
  • 2
  • 7
  • 20
  • Yes, you can get this error if you use a separate config file for connection strings, e.g. ``, and do not copy `connections.config` to the output directory. – Thane Plummer Nov 07 '16 at 22:04
1

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>
1

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.

yW0K5o
  • 913
  • 1
  • 17
  • 32
0

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

Amin Saqi
  • 18,549
  • 7
  • 50
  • 70
0

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>
Bala Kumar
  • 637
  • 3
  • 11
  • 18
0

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.

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
Oswaldo Alvarez
  • 4,772
  • 1
  • 22
  • 20
0

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

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

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
0

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.

Stefan Michev
  • 4,795
  • 3
  • 35
  • 30
0

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.

malt
  • 176
  • 8
0

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

0

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

Bala
  • 45
  • 6
0

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

Paul Totzke
  • 1,470
  • 17
  • 33
0

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.

GingerBeer
  • 888
  • 10
  • 11
0

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"/>

0

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

Atiq Baqi
  • 612
  • 1
  • 7
  • 16
0

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.

Honza P.
  • 1,165
  • 1
  • 11
  • 12
0

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>
Evilripper
  • 1,165
  • 1
  • 15
  • 26
0

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!

Thierry
  • 6,142
  • 13
  • 66
  • 117
0

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>
Tasos K.
  • 7,979
  • 7
  • 39
  • 63
0

Step 1:uninstall-package entity framework: This Command Uninstall Existing Entitymanger in The Project

Step 2:uninstall-package entity framework: This Command Install Latest Version Into Project

At Last ReBuild The Project It Will Works Good

0

I deleted the bin folder, rebuilt the solution, and included the generated bin folder back in the project. My code started working.

Timothy G.
  • 6,335
  • 7
  • 30
  • 46
Emy
  • 1
-1

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

Svein Terje Gaup
  • 1,424
  • 15
  • 29