Search code examples
c#asp.netasp.net-mvcasp.net-core-2.2

How to bind ApplicationDbContext to a View in ASP.Net Core 2.2


I need to bind ApplicationDbContext to my View for using models but its not working.

I have tried @using ProjectName.Data for accessing ApplicationDbContext but vain.

@using TailorManagementSystem.Data in the head

ApplicationDbContext dbContext = new ApplicationDbContext();

The error comes out to be "There is no argument given to that corresponds to the required formal parameter 'options' of ApplicationDbContext"


Solution

  • You have to inject it into the view:

    @inject TailorManagementSystem.Data.ApplicationDbContext Context
    

    Then you can use Context in your view.

    However, you should never actually do this. Views should have as little logic as possible. Things like querying a database should be handled in your controller action or via something like a view component, never in the view itself.