简体   繁体   中英

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

I am declaring a DBContext variable like this in my program:

class Program
{
    static MyDataContext context;

    // ...
}

but I get the following error:

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

My connection string in App.Config has the same name as the DBContext variable and works from a web app. 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.

Avoid using a context this way and prefer to adhere to using for disposable resources:

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM