1

I created a new ASP.NET project using this command

dotnet new mvc --auth Individual

It generates only Registration and Login actions. I need also create, read, update and delete actions for products model. But I could not create the DatabaseContext instance. I tried to create an object like this:

private ApplicationDbContext ctx = new ApplicationDbContext();

It says an error:

There is no argument given that corresponds to the required formal parameter 'options' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions)' [project-name]

This is the ApplicationDbContext.cs file:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }

So how to create the object of ApplicationDbContext class?

zshanabek
  • 4,270
  • 3
  • 19
  • 27

1 Answers1

0

The question is about creating the object of the ApplicationDbContext. The ApplicationDbContext class can be found in the IdentityModels.cs file for MVC project.

The automatic namespace for the classes in the Models folder is YourProjectName.Models

As to what goes for the options you could read it here:

What goes into DbContextOptions when invoking a new DbContext?

Given your connection string name as DefaultConnection, it likely goes like this:

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

Thus, to generate ApplicationDbContext object in your code, you could simply use the automatically generated namespace and generate the options to initialize the object like this:

using YourProjectName.Models; //initialize your .cs file with this
...
var options = new DbContextOptionsBuilder<ApplicationDbContext>();
options.UseSqlServer(Configuration.GetConnectionStringSecureValue("DefaultConnection"));
ApplicationDbContext context = new ApplicationDbContext(options); //somewhere else in the file

And then use it like: context.Users... or context.YourOtherTableNames.EFMethod...

Community
  • 1
  • 1
Ian
  • 30,182
  • 19
  • 69
  • 107