简体   繁体   English

如何在.Net控制台应用程序中实例化Entity Framework DBContext?

[英]How do you instantiate an Entity Framework DBContext in a .Net Console Application?

I am declaring a DBContext variable like this in my program: 我在程序中声明了这样的DBContext变量:

class Program
{
    static MyDataContext context;

    // ...
}

but I get the following error: 但我收到以下错误:

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. “ System.Data.Entity.Internal.AppConfig”的类型初始值设定项引发了异常。

My connection string in App.Config has the same name as the DBContext variable and works from a web app. 在我的连接字符串App.Config具有相同的名称DBContext变量,从一个Web应用程序的工作原理。 Has anyone else seen this? 其他人看到了吗?

And if I instantiate all in one line like this: 如果我在一行中实例化所有实例,如下所示:

class Program
{
    static MyDataContext context = new MyDataContext();

    // ...
}

instead of in main: 而不是主要的:

context = MyDataContext();

I get this error: 我收到此错误:

The type initializer for 'NLP.Program' threw an exception. “ NLP.Program”的类型初始值设定项引发了异常。

Avoid using a context this way and prefer to adhere to using for disposable resources: 避免以这种方式使用上下文,而宁愿坚持using可弃资源:

using(MyDataContext context = new MyDataContext(...))
{
    // ...
}

This does not solve your problem but is a first step to better code. 这不能解决您的问题,但是是改进代码的第一步。

EDIT: removed simply wrong answer. 编辑:删除根本错误的答案。 Better no answer than a wrong one... 没有答案总比错误的答案好...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Visual Studio 2017中的.NET Framework 4.5控制台应用程序引用.NET标准库? - How Do You Reference a .NET Standard Library from a .NET Framework 4.5 Console Application in Visual Studio 2017? 在 Entity Framework Core 中创建迁移时如何配置 DbContext? - How do you configure the DbContext when creating Migrations in Entity Framework Core? 如何在 web 应用程序中集中实体框架数据上下文? - How do you centralize the Entity Framework data context in a web application? 在 .NET 5 控制台应用程序中调用旧的 .NET 框架 DbContext class 库应用程序? - Calling older .NET Framework DbContext class library application within a .NET 5 console application? 如何在实体框架中识别DbContext? - How To identify DbContext in entity framework? 如何在Entity Framework 6中重命名DBContext - How to Rename DBContext in Entity Framework 6 如何使用 Entity Framework 6 在内存中创建 DbContext? - How do I create an in memory DbContext with Entity Framework 6? 如何在 Entity Framework Core 中将连接字符串传递给 DBContext? - How do I pass connection string to DBContext in Entity Framework Core? 如何将“/ x”选项参数合并到.NET控制台应用程序中? - How do you incorporate “/x” option parameters into a .NET console application? 如何使用Entity Framework + Mysql(在控制台应用程序中) - How to use Entity Framework + Mysql (in console application)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM