From d9e8bf8553c77bdf8a0ee30650d9687d393cb6da Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Wed, 16 Mar 2022 23:37:22 +1100 Subject: [PATCH] 10.4 Querying EF Core models -> use LINQ to query all categories and their products --- .../WorkingWithEFCore/Program.cs | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/Chapter10/WorkingWithEFCore/WorkingWithEFCore/Program.cs b/Chapter10/WorkingWithEFCore/WorkingWithEFCore/Program.cs index 25dcbcc..ff3ad4a 100644 --- a/Chapter10/WorkingWithEFCore/WorkingWithEFCore/Program.cs +++ b/Chapter10/WorkingWithEFCore/WorkingWithEFCore/Program.cs @@ -1,3 +1,26 @@ -using Packt.Shared; +using Microsoft.EntityFrameworkCore; +using Packt.Shared; -Console.WriteLine($"Using {ProjectConstants.DatabaseProvider} database provider."); \ No newline at end of file +Console.WriteLine($"Using {ProjectConstants.DatabaseProvider} database provider."); +QueryingCategories(); + +static void QueryingCategories() +{ + using (Northwind db = new()) + { + Console.WriteLine("Categories and how many products they have:"); + // a query to get all categories and their related products + IQueryable? categories = db.Categories? + .Include(c => c.Products); + if (categories is null) + { + Console.WriteLine("No categories found"); + return; + } + // execute query and enumerate results + foreach (var c in categories) + { + Console.WriteLine($"{c.CategoryName} has {c.Products.Count} products"); + } + } +} \ No newline at end of file