使用EF开发控制台CRUD程序时遇ConfigurationErrorsException问题求助
ConfigurationErrorsException: Configuration system failed to initialize
Only one<configSections>element allowed per config file and if present must be the first child of the root<configuration>element...
使用Entity Framework 6开发.NET Framework 4.7.2控制台应用,执行CRUD时触发上述异常。已确认app.config中仅包含一段连接字符串,尝试过清理重建解决方案、重启Visual Studio,问题仍未解决。
现有代码片段
app.config连接字符串配置
<connectionStrings> <add name="StudentsDbContext" connectionString="Data Source=localhost;Initial Catalog=students;Integrated Security=True;" providerName="System.Data.SqlClient" /> </connectionStrings>
StudentsDbContext代码
public class StudentsDbContext : DbContext { public DbSet<Student> Students { get; set; } }
Program入口代码
class Program { static void Main() { StudentsDbContext context = new StudentsDbContext(); while (true) // ..... } }
排查解决步骤
检查app.config完整结构
异常核心要求是<configSections>必须是<configuration>的第一个子元素,且只能存在一个。即使未手动添加,EF6自动生成的配置段如果位置错误也会触发问题。完整的合规结构如下:<?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" /> </configSections> <connectionStrings> <add name="StudentsDbContext" connectionString="Data Source=localhost;Initial Catalog=students;Integrated Security=True;" providerName="System.Data.SqlClient" /> </connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration>确保
configSections紧跟<configuration>标签之后,且唯一存在。重新安装EF6 NuGet包
若手动修改过配置导致结构错乱,可卸载EF6后重新安装,让NuGet自动修复app.config的正确结构。清理重复的configSections
打开完整的app.config文件,全局搜索<configSections>,删除多余的重复元素,只保留一个且放在最顶部。显式指定DbContext连接字符串
为避免自动匹配出错,可在DbContext构造函数中显式传入连接字符串名称:public class StudentsDbContext : DbContext { public StudentsDbContext() : base("StudentsDbContext") { } public DbSet<Student> Students { get; set; } }
内容的提问来源于stack exchange,提问作者Asmar J.

