Entity Framework Core Context Instance Options

asp.net-core c# entity-framework-core

Question

I am new on EF Core.

I have created my context which refers from appsettings.json

public APITestDBContext(DbContextOptions<APITestDBContext> options):base(options)
{
}

Working well. I able to update DB in Code First approach. But when I tried to make an instance from dbcontext, it's expecting option. I don't know what options that expecting.

private APITestDBContext db = new APITestDBContext();

There is no argument given that corresponds to the required formal parameter 'options' of 'APITestDBContext.APITestDBContext(DbContextOptions)'

What I need to write there?

1
0
5/20/2018 2:39:53 PM

Accepted Answer

What you did is fine that you supported dependency injection for your class, and In the ConfigureService Method in Startup.cs you mentioned how the injection to be resolved. So now when you need to create new like that. Your class requires a constructor parameter which you need to provide which will be the same parameter value in your startup class.

or create another overload for the constructor as below which accepts no parameters :

public APITestDBContext():base()
{
}

But to do that it will call DBContext.OnConfiguring() method to setup your db which you need to implement.

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Your Connection String");
    }
1
5/20/2018 6:14:37 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow