concept ReviewCount in category entity framework

appears as: ReviewCount, ReviewCount
Entity Framework Core in Action

This is an excerpt from Manning's book Entity Framework Core in Action.

It’s possible to create an SQL command that would produce the same output as listing 12.10, but would calculate the ReviewCount only once. This SQL command would be quicker than EF Core’s version at the time of writing (version 2.0).

Listing 13.10 SaveChangesWithReviewCheck method to fix invalidated cached values
public static class SaveChangesBookFixer
{
    public static int SaveChangesWithReviewCheck    #1  
        (this EfCoreContext context)
    {
        try
        {
            return context.SaveChanges();    #2  
        }
        catch (DbUpdateConcurrencyException ex)    #3  
        {
            var entityToFix = ex.Entries    #4  
                .SingleOrDefault(x => x.Entity is Book);    #4  
            if (entityToFix == null)    #5  
                throw;    #5  
            if ( FixReviewCachedValues(context, entityToFix))    #6  
                return context.SaveChangesWithReviewCheck ();    #6  
        }
        return 0;    #7  
    }

    private static bool FixReviewCachedValues(
        EfCoreContext context,
        EntityEntry entry)
    {
        var book = (Book) entry.Entity;    #8  
        var actualReviews = book.Reviews    #9  
            .Where(x =>    #9  
                context.Entry(x).State == EntityState.Added)    #9  
            .Union(context.Set<Review>().AsNoTracking()    #9  
                .Where(x => x.BookId == book.BookId))    #9  
            .ToList();    #9  
        var databaseEntity =    #10  
            context.Books.AsNoTracking()    #10  
            .SingleOrDefault(p => p.BookId == book.BookId);    #10  
        if (databaseEntity == null)    #11  
            return false;    #11  
        var databaseEntry = context.Entry(databaseEntity);    #12  

        //We need to fix the ReviewCount and the AverageReview 
        var countProp = entry.Property(nameof(Book.ReviewsCount));    #13  
        var averageProp = entry.Property(nameof(Book.AverageVotes));    #13  
        var reviewCount = actualReviews.Count;    #14  
        countProp.CurrentValue = reviewCount;    #15  
        countProp.OriginalValue =    #16  
            databaseEntry.Property(nameof(Book.ReviewsCount))    #16  
            .CurrentValue;    #16  
        averageProp.CurrentValue = reviewCount > 0    #17  
            ? actualReviews.Average(x => (double?) x.NumStars)  #17  
            : null;    #17  
        averageProp.OriginalValue =    #18  
            databaseEntry.Property(nameof(Book.AverageVotes))    #18  
            .CurrentValue;    #18  
        return true;    #19  
    }
}

#1   Method automatically handles any concurrency issues.
#2   Calls the normal SaveChanges method within a try/catch block. If it works, it returns. If there’s a DbUpdateConcurrencyException, it’ll enter the “catch” part and execute code to fix the problem.
#3   Handles only Book entities, so you filter those out.
#4   You expect only one Book concurrency issue, so you check that’s the case.
#5   If the entity isn’t a book, you rethrow the exception because you can’t handle it.
#6   Calls your private method to handle this book concurrency issue. If it returns true, it has updated the book entity.
#7   If someone deletes the book you were updating, you leave that as is and return 0 to say nothing was updated.
#8   You cast the entity to a book so that you can access the properties you know.
#9   Gets the combination of the reviews in the database and any new reviews being added. That’s what the cached values must match.
#10   Need to load the current values for the book entity in the database. You need that later to stop EF Core from seeing a concurrency error again.
#11   If there’s no book in the database, it’s deleted.
#12   Gets the EntityEntry class of the databaseEntity, because you need to access its currentValues
#13   Gets references to the PropertyEntry for the ReviewsCount and AverageVotes in the Book entity.
#14   Recalculates the reviews count by using the actual number of reviews
#15   Updates the ReviewsCount property to this recalculated value
#16   Sets the OriginalValue of the ReviewsCount property to the last read value. This stops EF Core from throwing a DbUpdateConcurrencyException again.
#17   Sets the AverageVotes value to the recalculated average votes value
#18   Sets the OriginalValue of the AverageVotes property to the last read value. This stops EF Core from throwing a DbUpdateConcurrencyException again.
#19   Returns true to say that SaveChanges needs to be called again to update the Book entity with the corrected data