MVC: Extracting One Record

Menu
Menu

Extracting One Record

Amending the Controller to use DbContext

Previously, we populated the 'Films' table so we can now look at extracting data and placing it into Views in the application.

Amend the controller Controllers/HomeController.cs so that it extracts a record from a table in the database. To do so the controller needs to be aware of the Dbcontext. Add a new private readonly variable for the database context (below the private readonly variable _logger).

CONTROLLER: Controllers/HomeController.cs

Now it is declared, the Dbcontext can be made available to the controller through dependency injection into the constructor.

CONTROLLER: Controllers/HomeController.cs

Dependency Injection is a software engineering technique related to 'Inversion of Control' (IoC). ASP.NET Core MVC controllers request dependencies explicitly via constructors. Above the HomeController contructor receives the DbContext as a parameter. This was possible because in ConfigureServices() method of Startup.cs the services.AddDbContext(..) method was used to register as a ApplicationDbContext as service.

Set up an Action in the Controller

Add a Task/Action to the controller called OneFilm. The URL called to see this will be localhost:5000/Home/OneFilm

CONTROLLER: Controllers/HomeController.cs

The Action stores Film data into a variable called model. This is done using the DbContext and its access to the Films data, on which the LINQ (Language Integrated Query) extension FirstOrDefault() method is called.

Create a View

Create a view at Views/Home/OneFilm.cshtml which will receive the model.

At the top of the View we'll add the @model directive @model YourAppName.Models.Film. This specifies the type of object that the view expects.

VIEW: Views/Home/OneFilm.cshtml

The Model is available to the view and so dot syntax can be used to extract values such as FilmTitle above. We can also use the Model to populate the ViewData["Title"] to give the page a unique title based on the film found.

Test your page at localhost:5000/Home/OneFilm.

Challenge: Amend the VIEW to include other fields from the 'Films' table.

Amend the CONTROLLER to use other LINQ (Language Integrated Query) extensions such as First(), Last() or LastOrDefault().