已定义重复的“entityFramework”部分 - EntityFramework6升级

5
我最近将我的WebAPI项目中的EntityFramework从v5升级到了v6。不幸的是,似乎某个配置文件中存在一个引用,其版本设置为v5.0。尽管我无法找到它的具体位置,但我会在下面发布我的web.config。
显示的错误是:“已定义重复的‘entityFramework’部分”。
我找不到重复的引用,但如果我删除单个引用,则会出现以下错误:
{"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)"}
这是我的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>

<

4个回答

15

我也遇到了同样的问题,因为我有一个运行EF6的虚拟目录和运行EF5的根目录。花费了我几个小时,但最终找到了解决方法:

在虚拟目录的Web.config文件中,删除或注释掉EF6的configSection(这样可以避免重复entityFramework部分),添加程序集绑定重定向(让它将根目录的EF5 configSection映射到EF6,但仅限于虚拟目录),最后删除所有<entityFramework>配置,以便它不会尝试在虚拟目录中查找EF6的configSection。我的新Web.config文件如下所示:

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

接下来我添加了一个DbConfiguration类到包含DbContext的程序集中(这基本上启用了EF6的代码优先配置)。例如:

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

这就是全部内容了,现在我可以让EF的两个版本共存。对于我来说,棘手的部分是弄清楚如何进行从EF5到EF6的AssemblyBinding重定向。同时请注意,我没有更改根Web.config中的任何内容。

希望这能帮助那些遇到同样问题的人。


我会给你web.config爵位!让我困惑的是为什么无法覆盖配置部分,或者阻止它在父级中继承(https://dev59.com/qXRA5IYBdhLWcg3w6SXZ)? - MiBu

11

问题与站点的根目录有关;我忘记了它指向另一个相关项目,该项目映射到虚拟目录。这导致加载了其他web.config文件。


那是在VS解决方案还是项目中?你在哪里改变“站点的根目录”?我遇到了和你一样的问题,如果有任何额外的提示,将不胜感激。 - Michel Triana
1
基本上,我一直在虚拟目录中工作,因此根目录的web.config和虚拟目录内部的web.config之间存在冲突。如果您正在使用带有多个ASP.NET项目的站点,并且这些项目分布在多个目录中,请查看其他web.config文件。 - John
我在使用IIS Express时遇到了这个问题,但是无法确定父级web.config的位置。所以...我只需让Visual Studio通过端口号重新映射到不同的目录即可。 - Ellesedil
我也曾在IIS Express中遇到这个问题。大约一年前,由于TFS问题,我将我的项目复制到了不同的本地C:文件夹中。我没有意识到IIS Express仍然将该路径作为我的站点根目录,并且还有我的新位置。所以我不得不编辑IIS Express正在使用的站点物理位置的条目。我花了很长时间才找到IIS Express使用的配置文件。请查看C:\ Users \ yourUserIDHere \ Documents \ IISExpress \ config \ applicationhost.config。那是我进行修复的地方。 - Greg Barth
2
这很糟糕。这意味着ASP.NET MVC项目在根目录和虚拟目录上有不同的配置,而且虚拟目录依赖于根目录。如果出于某种原因重新部署根目录,这将破坏虚拟目录。设计很差。 - Toolkit

2
很晚才回答,但我使用S/O作为个人参考,并最近遇到了这个问题,所以我想提供一个对我有效的解决方案。
这是因为您安装了2个版本的EF。只需转到NuGet软件包管理器并卸载您不想要的版本即可解决问题(例如,如果您有EF5和EF6,则可能要卸载EF5)。完成后可能需要重新启动计算机,但所有内容应该都可以正常工作。
希望这可以帮助您。如果您想让我详细解释步骤,请添加评论并告诉我。

很不幸,对我没有起作用 :( 我们的VS解决方案只有新的EF6包,因为最近从EF5升级。将web.config中的EF版本从6.0.0.0更改为5.0.0.0确实“修复”了它,但这是一个令人讨厌的临时hack。 - Zeek2

0

在父文件夹和虚拟文件夹的Web配置中保持相同的entityFramework版本,对我来说解决了这个问题。

如果您的项目中安装了较旧版本的entityFramework,请右键单击该项目,然后转到“管理NuGet包”,接着从左侧选择“在线搜索”选项,选择您想要的版本并进行安装。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接