Steve McNiven-Scott
Steve McNiven-Scott

Reputation: 1902

How do you just use a DBContext in dotnet Core

So lets say I just make a helper class and need to call the DB from inside a Static Method.

There is no argument given that corresponds to the required formal parameter 
'options' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions<‌​
ApplicationDbContext‌​>)' 

I can't seem to just do

    public static bool IsKeyValid(string key)
    {
        var isValid = false;

        if (!String.IsNullOrEmpty(key)) {
            isValid = new ApplicationDbContext().Children.Any(x => x.Token == key);
        }

        return isValid;
    }

So I know I can get my context from my controller and pass it in, but is that the only way?

I'm very confused because all the docs just kinda say "Hey, make a new context, look how easy it is" http://ef.readthedocs.io/en/latest/querying/basic.html#id3

Any help would be appreciated

enter image description here

Upvotes: 3

Views: 1533

Answers (1)

Sampath
Sampath

Reputation: 65978

If you need to create the context manually, then you can configure it as shown below.

var options = new DbContextOptionsBuilder<ApplicationDbContext>();
options.UseSqlServer(Configuration.GetConnectionStringSecureValue("DefaultConnection"));
_context = new ApplicationDbContext(options.Options); 

Please see this too : Configuring a DbContext

Upvotes: 2

Related Questions