Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a DbContext in EF Core

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

like image 454
john Cogdle Avatar asked Jun 10 '18 21:06

john Cogdle


People also ask

What is DbContext in EF core?

DbContext is a combination of the Unit Of Work and Repository patterns. DbContext in EF Core allows us to perform following tasks: Manage database connection. Configure model & relationship. Querying database.

How do I create a database context in .NET core?

To have a usable Entity Framework DBContext, we need to change the configuration of the application. We will need to add a connection string so that our DBContext knows which server to go to and which database to query. We will put the connection string in a JSON configuration file.

How do I create a context class in Entity Framework?

To use code-first for an existing database, right click on your project in Visual Studio -> Add -> New Item.. Select ADO.NET Entity Data Model in the Add New Item dialog box and specify the model name (this will be a context class name) and click on Add. This will open the Entity Data Model wizard as shown below.


1 Answers

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 } 
like image 120
Qamar Zaman Avatar answered Oct 17 '22 00:10

Qamar Zaman