User-270429056 posted
Hello,
I'm trying to run a C# method after a page is loaded. The method checks the database if a log entry is existing and if not it will write one. The log contains the Id of the page and the email of the current logged in user. This is set to only log once per day
so essentially it checks if email, page id, and if the current date is found, if not it will create an entry.
I'm currently starting the method at the end of OnGetAsync(), but I'm hoping it a better way to do this so that the loading speed of the page is not affected. Is there a way to do this?
This is the method that is called. If you see any way to improve this then I would be happy to learn about it.
private async Task RegisterUsageAsync(string customerId)
{
string email = HttpContext.User.Identity.Name;
if (email != null && DailyPageViews == null)
{
DailyPageViews dpv;
DateTime now = DateTime.Now.Date;
dpv = await _context.DailyPageViews
.FirstOrDefaultAsync(m => m.ViewerEmail == email && m.ViewedCustomerID == customerId && m.ViewDate == now);
if (dpv == null)
{
//Write to sql.
DailyPageViews newdpv = new DailyPageViews
{
ViewDate = now,
ViewerEmail = email,
ViewedCustomerID = customerId
};
//Is this needed? does it work to prevent another db read?
DailyPageViews = newdpv;
_context.DailyPageViews.Add(newdpv);
_context.SaveChanges();
}
}
}
Thanks.