简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM