From 21aa0981aef3bbea10bfc4904d8307df3f0e97ff Mon Sep 17 00:00:00 2001 From: Moussa Bourich Date: Thu, 6 Oct 2022 16:07:35 +0200 Subject: [PATCH] GetAuthors query optimization --- BenchmarkService.cs | 27 ++++++++++++++++++++++++++- Context/AppDbContext.cs | 2 +- Program.cs | 5 +++-- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/BenchmarkService.cs b/BenchmarkService.cs index d0a958d..045e5da 100644 --- a/BenchmarkService.cs +++ b/BenchmarkService.cs @@ -88,7 +88,32 @@ public List GetAuthors() [Benchmark] public List GetAuthors_Optimized() { - List authors = new List(); + using var dbContext = new AppDbContext(); + + var authors = dbContext.Authors + .Include(x => x.User) + .Include(x => x.Books) + .Where(x => x.Country == "Serbia" && x.Age == 27) + .OrderByDescending(x => x.BooksCount) + .Select(x => new AuthorDTO + { + UserFirstName = x.User.FirstName, + UserLastName = x.User.LastName, + UserEmail = x.User.Email, + UserName = x.User.UserName, + BooksCount = x.BooksCount, + AllBooks = x.Books + .Where(a => a.Published.Year < 1900) + .Select(y => new BookDto + { + Name = y.Name, + PublishedYear = y.Published.Year + }).ToList(), + AuthorAge = x.Age, + AuthorCountry = x.Country + }) + .Take(2) + .ToList(); return authors; } diff --git a/Context/AppDbContext.cs b/Context/AppDbContext.cs index a4c4b8b..c0a4f0b 100644 --- a/Context/AppDbContext.cs +++ b/Context/AppDbContext.cs @@ -7,7 +7,7 @@ public class AppDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder options) { - options.UseSqlServer("Server=localhost;Database=OptimizeMePlease;Trusted_Connection=True;Integrated Security=true;MultipleActiveResultSets=true"); + options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=OptimizeMePlease;Trusted_Connection=True;MultipleActiveResultSets=true"); } protected override void OnModelCreating(ModelBuilder modelBuilder) diff --git a/Program.cs b/Program.cs index b05ee2d..4bac143 100644 --- a/Program.cs +++ b/Program.cs @@ -26,16 +26,17 @@ static void Main(string[] args) //Debugging BenchmarkService benchmarkService = new BenchmarkService(); benchmarkService.GetAuthors(); + benchmarkService.GetAuthors_Optimized(); //Comment me after first execution, please. //IWillPopulateData(); - //BenchmarkRunner.Run(); + BenchmarkRunner.Run(); } public static void IWillPopulateData() { - string sqlConnectionString = @"Server=localhost;Database=OptimizeMePlease;Trusted_Connection=True;Integrated Security=true;MultipleActiveResultSets=true"; + string sqlConnectionString = @"Server=(localdb)\MSSQLLocalDB;Database=OptimizeMePlease;Trusted_Connection=True;MultipleActiveResultSets=true"; string workingDirectory = Environment.CurrentDirectory; string path = Path.Combine(Directory.GetParent(workingDirectory).Parent.Parent.FullName, @"script.sql");