C# EntityFramework.dll 中发生类型为“System.TypeInitializationException”的未处理异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17132698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:40:54  来源:igfitidea点击:

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

c#.netentity-frameworksqlite

提问by Joe Slater

I was trying to learn Entity Frameworkand SQLiteusing this tutorial. However, I get an error.

我试图使用本教程学习实体框架SQLite。但是,我收到一个错误。

The error thrown is:

抛出的错误是:

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Additional information: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.

EntityFramework.dll 中发生类型为“System.TypeInitializationException”的未处理异常

附加信息:“System.Data.Entity.Internal.AppConfig”的类型初始值设定项引发异常。

Here is the full error trace:

这是完整的错误跟踪:

System.TypeInitializationException: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. ---> System.Configuration.Configuration
ErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration>
element. (C:\Users\Ankur\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe.config line 11)
   at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
   at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
   at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
   at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
   --- End of inner exception stack trace ---
   at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
   at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
   at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
   at System.Configuration.ConfigurationManager.get_ConnectionStrings()
   at System.Data.Entity.Internal.AppConfig..ctor()
   at System.Data.Entity.Internal.AppConfig..cctor()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Internal.AppConfig.get_DefaultInstance()
   at System.Data.Entity.Internal.LazyInternalConnection..ctor(String nameOrConnectionString)
   at System.Data.Entity.DbContext..ctor()
   at ConsoleApplication1.ChinookContext..ctor()
   at ConsoleApplication1.Program.Main(String[] args) in c:\Users\Ankur\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs
:line 16

Here is the C# code:

这是 C# 代码:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new ChinookContext()) //error comes on this line
            {
            }
        }
    }

    class ChinookContext : DbContext
    {
    }
}

Here is file App.config:

这是文件App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.data>
    <DbProviderFactories>
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description="Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
    </DbProviderFactories>
  </system.data>
  <connectionStrings>
    <add name="ChinookContext" connectionString="Data Source=|DataDirectory|Chinook_Sqlite_AutoIncrementPKs.sqlite" providerName="System.Data.SQLite" />
  </connectionStrings>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.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>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

Here is file packages.config:

这是文件packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="5.0.0" targetFramework="net45" />
  <package id="System.Data.SQLite.x86" version="1.0.86.0" targetFramework="net45" />
</packages>

采纳答案by Marc Gravell

Read the message:

阅读消息:

Only one <configSections>element allowed per config file and if present must be the first child of the root <configuration>element.

<configSections>每个配置文件只允许一个元素,如果存在,必须是根<configuration>元素的第一个子 元素。

Move the configSections element to the top - just above where system.data is currently.

将 configSections 元素移动到顶部 - 就在 system.data 当前所在位置的上方。

回答by Hector Alvarez

Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSectionsnode in Web.configfile. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...

检查您的参考文献中的实体框架参考版本,并确保它与文件中的configSections节点匹配Web.config。就我而言,它指向我的 configSections 中的 5.0.0.0 版本,而我的参考是 6.0.0.0。我只是改变了它,它起作用了......

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

回答by irfan akkas

Just go to Web.Configfrom Mainfolder, not the one in ViewsFolder:

刚去Web.ConfigMain文件夹中,而不是在一个Views文件夹:

configSections

配置部分

section name="entityFramework" type="System.Data. .....,Version=" <strong>5</strong>.0.0.0"..

部分 name="entityFramework" type="System.Data. .....,Version=" <strong>5</strong>.0.0.0"..

<..>

<..>

ADJUST THE VERSION OF EntityFramework you have installed, ex. like Version 6.0.0.0"

调整您已安装的 EntityFramework 的版本,例如。像版本6.0.0.0"

回答by SonerZ

In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.

在静态类中,如果您从 xml 或 reg 获取信息,类会尝试初始化所有属性。因此,您应该控制 config 变量是否存在,否则属性将不会初始化,因此类。

Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.

检查 xml 引用变量是否存在,检查 reg 引用变量是否存在,如果它们不存在,请确保您处理。

回答by Sujeet

Check that right version is referenced in your project. E.g. the dll it is complaining about, could be from an older version and that's why there could be a version mismatch.

检查您的项目中是否引用了正确的版本。例如,它抱怨的 dll 可能来自旧版本,这就是可能存在版本不匹配的原因。

回答by Akbar Badhusha

I had this issue when i refereed a library project from a console application, and the library project was using a nuget package which is not refereed in the console application. Referring the same package in the console application helped to resolve this issue.

当我从控制台应用程序推荐一个库项目时,我遇到了这个问题,并且该库项目使用了一个未在控制台应用程序中引用的 nuget 包。在控制台应用程序中引用相同的包有助于解决此问题。

Seeing the Inner exception can help.

查看内部异常会有所帮助。