EF Core: How to best aggregate over related entitiy properties

Viewed 44

Let's say I have a list Books and a list BooksRead, where I could track if I have read a book, so I have an Entity "Book" and an entity "BookRead".

Everytime I assign a BookRead entity to Book, I want a counter on Book to increment (property: TimesRead).

I have implemented such a scenario in different ways already. One time using a NotMapped property, where I do something like this:

[NotMapped]
int TimesRead => ReadEntries.Count

But because I use a component, that cannot sort by a property which is not mapped, I switched it to a property that is mapped. Everytime I now add a BookRead entry, or delete one, I also update the corresponding "TimesRead" value. As there are different places in my applications a user can add such an entry, I had to include this calculation in multiple places, so I wonder if there is better approach.

Also I switched my AverageRating property to mapped, which is even more bothering, as the rating can be set on various pages.

I had a look at calculated columns, but I believe they only work for data that is in the same table.

There is also the INotifyPropertyChanged interface, so I could theoretically work with events. But I'm not to fond of this idea.

What would be a clean approach for this scenario?

0 Answers
Related