From 184df1723c05cd98d8807d83b99ff8cde4eec61f Mon Sep 17 00:00:00 2001 From: ralcaraz Date: Mon, 26 Sep 2022 18:20:49 -0700 Subject: [PATCH 1/2] Added optimization --- BenchmarkService.cs | 43 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/BenchmarkService.cs b/BenchmarkService.cs index d0a958d..4ed9546 100644 --- a/BenchmarkService.cs +++ b/BenchmarkService.cs @@ -1,4 +1,5 @@ -using BenchmarkDotNet.Attributes; +using System; +using BenchmarkDotNet.Attributes; using Microsoft.EntityFrameworkCore; using OptimizeMePlease.Context; using System.Collections.Generic; @@ -88,9 +89,45 @@ public List GetAuthors() [Benchmark] public List GetAuthors_Optimized() { - List authors = new List(); + using var dbContext = new AppDbContext(); + + var bookCutoffDate = new DateTime(1900, 1, 1); + + var youngSerbianAuthorQuery = dbContext + .Authors + .Where(x => x.Country == "Serbia" && x.Age == 27) + .OrderByDescending(x => x.BooksCount) + .Take(2) + .Select(x => new AuthorDTO + { + UserCreated = x.User.Created, + UserEmailConfirmed = x.User.EmailConfirmed, + UserFirstName = x.User.FirstName, + UserLastActivity = x.User.LastActivity, + UserLastName = x.User.LastName, + UserEmail = x.User.Email, + UserName = x.User.UserName, + UserId = x.User.Id, + RoleId = dbContext.UserRoles.Where(y => y.UserId == x.UserId).Select(u => u.RoleId).FirstOrDefault(), + BooksCount = x.BooksCount, + AllBooks = dbContext.Books + .Where(b => b.Published < bookCutoffDate) + .Where(b => b.AuthorId == x.Id) + .Select(y => new BookDto + { + Id = y.Id, + Name = y.Name, + Published = y.Published, + ISBN = y.ISBN, + PublisherName = y.Publisher.Name + }).ToList(), + AuthorAge = x.Age, + AuthorCountry = x.Country, + AuthorNickName = x.NickName, + Id = x.Id + }); - return authors; + return youngSerbianAuthorQuery.ToList(); } } } From edd32c93a5e03f7bc107ff6d58cdf7c0bd9e1730 Mon Sep 17 00:00:00 2001 From: ralcaraz Date: Mon, 26 Sep 2022 18:43:27 -0700 Subject: [PATCH 2/2] Added missing property in final query --- BenchmarkService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/BenchmarkService.cs b/BenchmarkService.cs index 4ed9546..7ba996b 100644 --- a/BenchmarkService.cs +++ b/BenchmarkService.cs @@ -119,7 +119,8 @@ public List GetAuthors_Optimized() Name = y.Name, Published = y.Published, ISBN = y.ISBN, - PublisherName = y.Publisher.Name + PublisherName = y.Publisher.Name, + PublishedYear = y.Published.Year }).ToList(), AuthorAge = x.Age, AuthorCountry = x.Country,