I have 3 main columns (Points, TotalPoints, DateCreated) in a table using Entity Framework.
Scenario - Think of the "Fun Arcade" where you earn tokens for playing games and can then exchange those tokens for gifts. So your "Points" count or token count will go up and down as you use the application.
What I want - I'd like to see if Entity Framework can calculate the "TotalPoints" column, so that I don't have to do it every time a new "Point" entity is added to the table.
I know I can create a calculated column value that computes values from the same row (ex. first name col + last name col => full name column) But I want to sum up all values from the "Points" column for that user, so that the last row inserted (based on the DateCreated column) has the sum of all the points for that user.
ex. Point entity
points 1, totalPoints 1, dateCreated
points 3, totalPoints 4, dateCreated
points 2, totalPoints 6, dateCreated
points -1, totalPoints 5, dateCreated
points 2, totalPoints 7, dateCreated
FYI - I can also remove points, as seen above, if the user exchanges them for a gift.
QUESTION - Is this possible with fluent API and EF Core or do I have to manually calculate it every time I insert a new Point entry?
EDIT - I can do it manually and it seems to work ok. But I only have a few rows so far, so not sure about the performance with a few thousand rows for each user?
Here is what I have done.
When inserting a new "Point" entity I can calculate the sum of the users "Points" like this.
var totalPoints = userFromRepo.UserPoints.Sum(p => p.Points);
var point = new UserPoint() { Points = 1, TotalPoints = totalPoints+1, UserId = userFromRepo.Id, DateCreated = DateTime.UtcNow, UserPointType = UserPointType.Tip };
_unitOfWork.Repository<UserPoint>().Add(point);
and when I fetch the user data on log in, including the points, I do fetch based on the last "Point" inserted. This saves any time of doing some type of .SUM() or calculation each time a user logs in.
Ex. of getting users total points on log in
user.UserPoints.OrderByDescending(p => p.CreatedDate).LastOrDefault().TotalPoints)