How to instantiate a DbContext in EF Core

john Cogdle picture john Cogdle · Jun 10, 2018 · Viewed 48.9k times · Source

I have setup .net core project and db context also. But i cant start using dbContext yet due this error-

"there is no argument given that corresponds to the required formal parameter 'options'"

Controller:

public IActionResult Index()
{
    using (var db = new BlexzWebDb())
    {

    }
    return View();
}

Dbcontext Code:

public class BlexzWebDb : DbContext
{
    public BlexzWebDb(DbContextOptions<BlexzWebDb> options)
       : base(options)
    { }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<AssignedRole> AssignedRoles { get; set; }

}

error picture attached. Whats the possible fix for that issue? Thanks in advance

pic

Answer

Qamar Zaman picture Qamar Zaman · Apr 8, 2019

Instantiate new object of DbContext from ConnectionString

var connectionstring = "Connection string";

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
    optionsBuilder.UseSqlServer(connectionstring);


ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options);

// Or you can also instantiate inside using

using(ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options))
{
   //...do stuff
}