koviroli
koviroli

Reputation: 1453

MVC Use DbContext in other controller

I have two different controllers.

One is a came by default ASP.NET MVC Core :

public ManageController(
  UserManager<ApplicationUser> userManager,
  SignInManager<ApplicationUser> signInManager,
  IEmailSender emailSender,
  ILogger<ManageController> logger,
  UrlEncoder urlEncoder)
{
    _userManager = userManager;
    _signInManager = signInManager;
    _emailSender = emailSender;
    _logger = logger;
    _urlEncoder = urlEncoder;
}

and my own that I made with scaffolding:

public CarsController(CarsContext context)
{
    _context = context;
}

.

What I want to achieve: I'd like to use my CarsContext in one of ManageController's action method, but I don't know how could I instatiate, because CarsContext constructor looks like this:

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

. I don't know what could I add to constructor from a method in ManageController.

The task I'd like to achieve is to get cars from my CarsContext, to display those.

My another idea is to call the index method from my CarsController in method of ManageController, but also I don't know how to get it.

Upvotes: 4

Views: 599

Answers (1)

Kapil Ghimire
Kapil Ghimire

Reputation: 101

For this you can inject CarsContext to ManageController as you are injecting in CarsController and dependency injection framework will take care of rest

But do register CarsContext in dependency injection framework.

Upvotes: 2

Related Questions