简体   繁体   中英

How to get dbcontext access without an HTML page?

How can I get access to the dbcontext without an HTML page? I have a WebAPI project in which the classes from the HTML page can access the database, like this:

    public class CreateModel : PageModel
    {
       private readonly Home5.Models.Home5Context _context;

       public CreateModel(Home5.Models.Home5Context context)
       {
           _context = context;
       }

       public IActionResult OnGet()
       {
           return Page();
       }
    }

But when I create classes of my own, I can't access the context, because I can't create an instance of the class without having the context to give it to the constructor.

This sample shows the steps that are necessary to create a Web API that accesses a database using entity framework.

In order to use your Home5Context , the crucial steps are the following:

File startup.cs

Register the context with the dependency injection container. This is the component that creates the controller instances and provides them with an instance of your context, if configured correctly:

services.AddDbContext<Home5Context>(opt =>
           opt.UseInMemoryDatabase("Home5Database"));

Please note that there are several other options besides an InMemoryDatabase. The following documentation shows most of them.

Controller

Inject the context into the controller:

public class MyController : ControllerBase
{
    private readonly Home5Context _context;

    public TodoItemsController(Home5Context context)
    {
        _context = context;
    }

    // ...

After that, you can use the context and access the database in the controller.


Please see the sample or the code . Maybe it helps to follow the sample in a new project and then change your current project.

When I have a random class, how can i get an instance of context.

Sample:

public class work()
{
    public void setValue()
    {
       var context = await _context.firstordefaultasync(....);
       context......
       //Work with that context
       ...save context...
    }
}

In this form I cant create an instance of the class for working with it:

public class MyController : ControllerBase
{
    private readonly Home5Context _context;

    public TodoItemsController(Home5Context context)
    {
        _context = context;
    }
// ...

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