@using Microsoft.EntityFrameworkCore
@using MudBlazor
@using OpenArchival.DataAccess
@page "/articles/{ArticleIdString}"
@if (_article is not null)
{
@if (_article.ArtifactGroupings.Any()) {
{
Related Artifacts
@foreach(ArtifactGrouping grouping in _article.ArtifactGroupings)
{
@if (grouping.ChildArtifactEntries[0].Files.Any())
{
}
@grouping.Title
@grouping.Description
}
}
}
@_article.Title
Posted: @_article.CreationTime.Hour:@_article.CreationTime.Minute @_article.CreationTime.Month/@_article.CreationTime.Day/@_article.CreationTime.Year
Updated: @_article.ModifiedTime.Hour:@_article.ModifiedTime.Minute @_article.ModifiedTime.Month/@_article.ModifiedTime.Day/@_article.ModifiedTime.Year
Tags:
@((MarkupString)_article.Content)
}
@inject IArtifactGroupingProvider GroupingProvider;
@inject NavigationManager NavigationManager;
@inject IDbContextFactory ContextFactory;
@code {
[Parameter]
public string ArticleIdString { get; set; }
///
/// The converted grouping id from the URL
///
private int _articleId { get; set; }
private BlogPost _article { get; set; } = default!;
protected override async Task OnParametersSetAsync()
{
if (!int.TryParse(ArticleIdString, out int articleId))
{
NavigationManager.NavigateTo("/article-not-found");
return;
}
_articleId = articleId;
await using var context = await ContextFactory.CreateDbContextAsync();
// --- FIX: Added .Include(a => a.Views) AND .FirstOrDefaultAsync(a => a.Id == _articleId)
var article = await context.BlogPosts
.Include(a => a.Views)
.Include(a => a.ArtifactGroupings)
.ThenInclude(g => g.ChildArtifactEntries)
.ThenInclude(e => e.Files)
.Include(article=>article.Views)
.Include(article=>article.Tags)
.Include(article=>article.MainPhoto)
.FirstOrDefaultAsync(a => a.Id == _articleId); // <-- FIX 2: Filter by the correct ID
if (article is null)
{
NavigationManager.NavigateTo("/article-not-found");
return;
}
_article = article;
// --- This logic will now work correctly ---
if (_article.Views is null)
{
// This article has never been viewed, create a new view count
var viewCount = new BlogPostViewCount() { Post = _article, Views = 1 };
context.Add(viewCount); // Add the new count to the context
_article.Views = viewCount; // Associate it with the article
}
else
{
// It has been viewed, just increment the count
_article.Views.Views++;
}
await context.SaveChangesAsync(); // This will now correctly INSERT or UPDATE
// StateHasChanged() is not strictly necessary here, but doesn't hurt.
StateHasChanged();
await base.OnParametersSetAsync();
}
}