Our last look at LINQ demonstrates the ability to create calculated columns. We know that each Country has an Area and a Population. The Density would be Population divided by Area to get people per square mile. This match could be done client side in JavaScript or server side with some C# syntax. Instead, we will make a new data model that inherits from Country.cs called CountryStat.cs. It will have an additional member called Density.
In the Pages/Countries/Detail.cshtml.cs page, we will retrieve a single CountryStat
object instead of a Country. The final step will be the addition of a new field in the page markup.
Instructions
The new file Models/CountryStat.cs is open. Make this class inherit from Country.
Add a new member for population Density as a nullable float. Add a [Display]
annotation with a Name of "Ppl/SqMi"
.
Open the file Pages/Countries/Detail.cshtml.cs. Add a using statement for LINQ:
- System.Linq
Replace the Country
member type with CountryStat
.
Add a LINQ query at the top of the OnGetAsync()
method:
var country = from c in _context.Countries where c.ID == id select new CountryStat { ID = c.ID, ContinentID = c.ContinentID, Name = c.Name, Population = c.Population, Area = c.Area, UnitedNationsDate = c.UnitedNationsDate, Density = c.Population / c.Area };
Assign the result of the query to the Country member.
Open the file Pages/Countries/Detail.cshtml. Add a new <div>
at the bottom of the markup for the Density field. You can copy one of the other fields as a template:
<div class="d-flex"> <div class="p-2 bg-primary text-white text-right" style="flex:0 0 15%"> @Html.DisplayNameFor(model => model.Country.Density) </div> <div class="p-2 border-right border-bottom border-primary" style="flex:1 0 auto"> @Html.DisplayFor(model => model.Country.Density) </div> </div>
Browse the list of Countries and select Detail on a few. You should see the calculated population density.