.NET4.5下安装EntityFramework5.0.0运行时初始化异常求助
解决EF5.0在MVC4(.NET4.5)中初始化
AppConfig的异常问题 嘿,这个问题我之前也碰到过!你遇到的The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception错误,本质是Web.Config里的Entity Framework配置节和你实际安装的EF版本完全不匹配——你装的是EF5.0,但config里引用的是EF6.0的程序集信息,这就导致初始化上下文的时候找不到正确的类型了。
下面是具体的修复步骤,跟着做就能解决问题:
1. 修正configSections中的EF配置节点
打开Web.Config,找到<configSections>里的entityFramework节点,把版本号从6.0.0.0改成5.0.0.0,修改后的代码如下:
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
2. 删除EF6专属的<entityFramework>配置块
EF5并不使用EF6那种独立的<entityFramework>配置节点,所以直接把整个块删掉就行:
<!-- 把这段EF6的配置彻底删掉 --> <entityFramework> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework>
3. 确认项目引用的EF版本正确
右键你的项目 → 选择「管理NuGet程序包」,切换到「已安装」标签,确认Entity Framework的版本是5.0.0。如果不小心装了EF6,先卸载它,再重新安装EF5.0.0版本。
4. 验证连接字符串(可选但重要)
你的连接字符串看起来格式没问题,但要确保:
- 数据库服务器
DESKTOP-DO6F13P能被你的应用正常访问 sa账号的密码sa@123正确,且该账号拥有mvctrialdbase数据库的读写权限
修复后的核心配置示例
修改后的Web.Config核心部分大概是这样的:
<configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <!-- 其他appSettings、system.web等配置保持不变 --> <connectionStrings> <add name="EmployeeContext" providerName="System.Data.SqlClient" connectionString="SERVER=DESKTOP-DO6F13P;DATABASE=mvctrialdbase;uid=sa;pwd=sa@123;"/> </connectionStrings> </configuration>
做完这些修改后,清理项目(菜单栏→生成→清理解决方案),然后重新生成项目,再运行程序应该就能正常初始化EmployeeContext并查询到指定ID的员工记录了。
内容的提问来源于stack exchange,提问作者Sumeet Kumar
相关产品推荐
相关产品推荐

