Extracting More Data
Ensure DbContext is Set up
In the previous example (Extracting Data) the DbContext had already been made availble to the Controller/HomeController. As such we don't need to repeat that step here but be aware you will need a DbContext if one has not already been made available to the Controller.
Set up an Action in the Controller
Add a Task/Action to the controller called AllFilms. The URL called to see this will be localhost:5000/Home/AllFilms. Amend the Action as follows to generate a List.
The Action creates a List of 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 Method ToList() is called.
Create a View
Create a view at Views/Home/AllFilms.cshtml which will receive the model.
The Model is available to the view and can be looped using a foreach. Each @item representss a Film object extracted into a List by the controller. As such dot syntax can be used to extract values such as FilmTitle above.
Refine the View
Refine the HTML of the View to take advantage of the CSS provided. We can also make use of the FilmImage value in the database to dynamically load in an image from the wwwroot/images folder.
Changing the Query
The query returns all records. We could amend this to only list films with a '12' certificate.
In SQL we would aim to write:
In LINQ Query Syntax the query will be:
Amend the AllFilms() Action as follows:
Challenge: Amend the VIEW above to include other fields from the Films table.
Amend the <img> to use a dynamically produced alt value from the FilmTitle value in the database.
Produce other queries such as by FilmTitle or FilmPrice and order the results. For example list all the films with a FilmPrice over £2 and order them by the most expensive first.