5

I have recently updated EntityFramework in my WebAPI project from v5 to v6. Unfortunately it seems like somewhere, somehow, there is a reference that exists in some config somewhere that is set to v5.0. I can't seem to find it though; I will post my web.config below.

The error that shows up is:

There is a duplicate 'entityFramework' section defined.

I can't find that duplicate reference, but if I remove the single reference, then I get an error saying:

{"Message":"An error has occurred.","ExceptionMessage":"Could not load file or assembly 'EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)","ExceptionType":"System.IO.FileLoadException","StackTrace":" at System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)\r\n at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)\r\n at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)\r\n at System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord factoryRecord)\r\n at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)"}

Here is my web.config:

<?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.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></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="None" />
        <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>
        <profile defaultProvider="DefaultProfileProvider">
          <providers>
            <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
          </providers>
        </profile>
        <membership defaultProvider="DefaultMembershipProvider">
          <providers>
            <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
          </providers>
        </membership>
        <roleManager defaultProvider="DefaultRoleProvider">
          <providers>
            <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
          </providers>
        </roleManager>
        <!--
                If you are deploying to a cloud environment that has multiple web server instances,
                you should change session state mode from "InProc" to "Custom". In addition,
                change the connection string named "DefaultConnection" to connect to an instance
                of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
          -->
        <sessionState mode="InProc" customProvider="DefaultSessionProvider">
          <providers>
            <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
          </providers>
        </sessionState>
      </system.web>
      <system.webServer>
        <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>
      </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="1.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="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Core.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="v11.0" />
          </parameters>
        </defaultConnectionFactory>
        <providers>
          <provider invariantName="System.Data.Entity.Core.SqlClient" type="System.Data.Entity.Core.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
    </configuration>

<

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
John
  • 2,894
  • 2
  • 20
  • 25

4 Answers4

15

I was running into the exact same problem with having a Virtual Directory running EF6 and the root directory running EF5. Took me a few hours but I found a fix:

In the virtual directory Web.config, remove/comment out the configSection for EF6 (this stops you from duplicating the entityFramework section), add an assembly binding redirect (so it maps the root's EF5 configSection to EF6, but only in the Virtual Directory) and finally remove all the <entityFramework> configuration so it doesn't try to look for a configSection for EF6 in the Virtual Directory. My new Web.config file looks like this:

<configuration>
  <!--<configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.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>-->

... rest of configuration ...

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <!--<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>-->

Next I added a DbConfiguration class to the assembly that contains the DbContext (this basically enables the EF6 code first configuration). For example:

public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        SetDefaultConnectionFactory(new SqlConnectionFactory("Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True"));
    }
}

And that was it, now I can have both EF versions working along each other. The tricky part for me was figuring out how to do the AssemblyBinding from EF5 to EF6 redirect. Also notice that I didn't change anything in the root Web.config.

Hopefully this helps someone out there having the same issue.

ejbarrios
  • 151
  • 2
  • I would give you web.config knighthood! Thing that baffles me is why is impossible to override config section, or to stop it in parent from inheriting (http://stackoverflow.com/questions/782252/avoid-web-config-inheritance-in-child-web-application-using-inheritinchildapplic )? – MiBu Apr 18 '14 at 18:05
11

The problem was related to the root directory of the site; I forgot it was pointing to another related project, with this project mapped to a virtual directory. This lead to the other web.config being loaded.

John
  • 2,894
  • 2
  • 20
  • 25
  • Was that in the VS solution, or project? Where do you change the "root directory of the site". I'm having the same problem as you do,any additional hints will be appreciated. – Michel Triana Feb 20 '14 at 14:09
  • 1
    Basically I had been working in a virtual directory of a site, so there was a duplicate conflict between the web.config of the root directory, as well as inside the virtual directory. If you are using a site with multiple asp.net projects in multiple directories look around for other web.config's – John Feb 20 '14 at 21:10
  • I encountered this issue in IIS Express, but couldn't determine where to find the parent web.config. So... I just had Visual Studio remap to a different directory via port number. – Ellesedil Dec 15 '14 at 15:42
  • I had this problem too running in IIS Express. I had copied my project to a different local C: folder due to TFS issues about a year before. I didn't realize that IIS Express still had that path as the root for my site, and also had my new location. So I had to edit the entry for the physical location of the site that IIS Express was using. It took me a long time to locate the config file IIS Express uses. Look in C:\Users\yourUserIDHere\Documents\IISExpress\config\applicationhost.config. That's where I made my fix. – Greg Barth May 11 '15 at 16:18
  • 2
    this sucks. This means ASP.NET MVC project has different config for root and for VD, also VD depends on the root. If I redeploy root for some reason, this breaks the VD. Poor design – Toolkit Nov 23 '15 at 08:02
2

I know its a bit late to answer but I use S/O as a personal reference and I ran into this problem myself recently so I would like to offer a solution that worked for me.

This is happening simply because you have 2 versions of EF installed. Simply go to the nugget package manager and uninstall the version you don't want (i.e. if you have 5 and 6 of EF, you might want to uninstall EF5). When complete a restart might be required but all should work after.

Hope this helps. If you want me to explain in more details the step by step process just add a comment and let me know.

Francis Rodgers
  • 4,565
  • 8
  • 46
  • 65
  • Didn't work for me unfortunately :( Our VS solution only has the new EF6 package, since the recent upgrade from EF5. Changing the version of EF in the web.config from 6.0.0.0 to 5.0.0.0 did "fix" it but it's a nasty, temporary hack. – Zeek2 Sep 01 '21 at 15:57
0

Keeping the same entityFramework versions in both parent and virtual folder web configs fixes the issue for me.

If you have an older version of the entityFramework installed in the project, right click on the project then go to "Manage NuGet Packages" and then select "search online" option from the left and select version you want and install it.

Satish Shetty
  • 303
  • 2
  • 10