Code First无法启用迁移

Iva*_*ono 15 c# entity-framework sql-server-2008-r2 ef-code-first

我正在尝试启用迁移,但它正在抛出异常:

检查上下文是否以现有数据库为目标... System.TypeInitializationException:'System.Data.Entity.Migrations.DbMigrationsConfiguration`1'的类型初始值设定项引发异常.---> System.TypeInitializationException:'System.Data.Entity.Internal.AppConfig'的类型初始值设定项引发了异常.---> System.Configuration.ConfigurationErrorsException:配置系统初始化失败---> System.Configuration.ConfigurationErrorsException:必须在'section'标签上指定'name'属性.

我假设App.config文件没有正确设置(当我添加EF包时它自动设置).我所做的就是添加连接字符串:

<?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>
   <add Name="MyContext" connectionString="data source=MYSERVER;initial catalog=CodeFirstTest;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
 </connectionStrings>

 <entityFramework>
   <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
     <parameters>
       <parameter value="v11.0" />
     </parameters>
   </defaultConnectionFactory>
   <providers>
     <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
   </providers>
 </entityFramework>
</configuration>
Run Code Online (Sandbox Code Playgroud)

我正在使用SQL Server 2008 R2.

因为我有一个连接字符串,我不相信我需要defaultconnectionfactory.我对么?(注意:即使没有本节,我仍然会得到相同的例外)

我还缺少什么?

小智 50

当我的<connectionString />条目位于Web.config的顶部时,我遇到了同样的问题<configuration>.然后我尝试了之前移动它</configuration>,它工作.

  • 正如未来的读者所知,如果定义了任何自定义配置节,那么`<configuration>`之后的第一个元素必须是`<configSections>`.实体框架添加了一个名为`<entityFramework>`的自定义配置部分.因此,特别是在使用实体框架时,如果在"<configuration">之后放置其他任何内容,则会破坏您的应用程序. (7认同)

ski*_*rks 7

这主要与配置文件有关.所以实际的堆栈跟踪有助于"System.Configuration.ConfigurationErrorsException".可能有很多原因,但它们主要包括配置文件中的更正,如前所述.下面给出了几个与此不大的可能性(但是堆栈确实告诉我们)

  1. 一个可能的原因可能是,启用迁移的项目可能与启动项目不同.所以一定要将-StartUpProject添加到你的nuget命令中.
  2. 在两个不同项目的情况下,所使用的实体框架的版本可以是不同的.