[英]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.