Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions src/Web/Data/BlogDbContext.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
using Microsoft.EntityFrameworkCore;
using MongoDB.EntityFrameworkCore.Extensions;
using MyBlog.Domain.Entities;

namespace MyBlog.Web.Data;

public sealed class BlogDbContext(DbContextOptions<BlogDbContext> options) : DbContext(options)
{
public DbSet<BlogPost> BlogPosts => Set<BlogPost>();
public DbSet<BlogPost> BlogPosts => Set<BlogPost>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var entity = modelBuilder.Entity<BlogPost>();
entity.ToCollection("blogposts");
entity.HasKey(p => p.Id);
entity.Property(p => p.Version).IsConcurrencyToken();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var entity = modelBuilder.Entity<BlogPost>();
entity.ToCollection("blogposts");
entity.HasKey(p => p.Id);
entity.Property(p => p.Version).IsConcurrencyToken();
}
}
8 changes: 3 additions & 5 deletions src/Web/Data/BlogPostMappings.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
using MyBlog.Domain.Entities;

namespace MyBlog.Web.Data;

internal static class BlogPostMappings
{
internal static BlogPostDto ToDto(this BlogPost post) => new(
post.Id, post.Title, post.Content, post.Author,
post.CreatedAt, post.UpdatedAt, post.IsPublished);
internal static BlogPostDto ToDto(this BlogPost post) => new(
post.Id, post.Title, post.Content, post.Author,
post.CreatedAt, post.UpdatedAt, post.IsPublished);
}
84 changes: 40 additions & 44 deletions src/Web/Data/MongoDbBlogPostRepository.cs
Original file line number Diff line number Diff line change
@@ -1,53 +1,49 @@
using Microsoft.EntityFrameworkCore;
using MyBlog.Domain.Entities;
using MyBlog.Domain.Interfaces;

namespace MyBlog.Web.Data;

public sealed class MongoDbBlogPostRepository(IDbContextFactory<BlogDbContext> contextFactory)
: IBlogPostRepository
: IBlogPostRepository
{
public async Task<BlogPost?> GetByIdAsync(Guid id, CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
return await ctx.BlogPosts.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == id, ct);
}
public async Task<BlogPost?> GetByIdAsync(Guid id, CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
return await ctx.BlogPosts.AsNoTracking()
.FirstOrDefaultAsync(p => p.Id == id, ct);
}

public async Task<IReadOnlyList<BlogPost>> GetAllAsync(CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
return await ctx.BlogPosts.AsNoTracking()
.OrderByDescending(p => p.CreatedAt)
.ToListAsync(ct);
}
public async Task<IReadOnlyList<BlogPost>> GetAllAsync(CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
return await ctx.BlogPosts.AsNoTracking()
.OrderByDescending(p => p.CreatedAt)
.ToListAsync(ct);
}

public async Task AddAsync(BlogPost post, CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
await ctx.BlogPosts.AddAsync(post, ct);
await ctx.SaveChangesAsync(ct);
}
public async Task AddAsync(BlogPost post, CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
await ctx.BlogPosts.AddAsync(post, ct);
await ctx.SaveChangesAsync(ct);
}

public async Task UpdateAsync(BlogPost post, CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
var entry = ctx.Attach(post);
// Version was incremented by post.Update(); the original value in the DB is Version - 1.
// EF Core uses OriginalValue in the WHERE filter to detect concurrent modifications.
entry.Property(p => p.Version).OriginalValue = post.Version - 1;
entry.State = EntityState.Modified;
await ctx.SaveChangesAsync(ct);
}
public async Task UpdateAsync(BlogPost post, CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
var entry = ctx.Attach(post);
// Version was incremented by post.Update(); the original value in the DB is Version - 1.
// EF Core uses OriginalValue in the WHERE filter to detect concurrent modifications.
entry.Property(p => p.Version).OriginalValue = post.Version - 1;
entry.State = EntityState.Modified;
await ctx.SaveChangesAsync(ct);
}

public async Task DeleteAsync(Guid id, CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
var post = await ctx.BlogPosts.FindAsync([id], ct);
if (post is not null)
{
ctx.BlogPosts.Remove(post);
await ctx.SaveChangesAsync(ct);
}
}
public async Task DeleteAsync(Guid id, CancellationToken ct = default)
{
await using var ctx = await contextFactory.CreateDbContextAsync(ct);
var post = await ctx.BlogPosts.FindAsync([id], ct);
if (post is not null)
{
ctx.BlogPosts.Remove(post);
await ctx.SaveChangesAsync(ct);
}
}
}
5 changes: 1 addition & 4 deletions src/Web/Features/BlogPosts/Create/CreateBlogPostCommand.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using MediatR;
using Domain.Abstractions;

namespace MyBlog.Web.Features.BlogPosts.Create;

public sealed record CreateBlogPostCommand(string Title, string Content, string Author)
: IRequest<Result<Guid>>;
: IRequest<Result<Guid>>;
43 changes: 18 additions & 25 deletions src/Web/Features/BlogPosts/Create/CreateBlogPostHandler.cs
Original file line number Diff line number Diff line change
@@ -1,30 +1,23 @@
using MediatR;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using MyBlog.Domain.Entities;
using MyBlog.Domain.Interfaces;
using Domain.Abstractions;

namespace MyBlog.Web.Features.BlogPosts.Create;

public sealed class CreateBlogPostHandler(
IBlogPostRepository repo,
IMemoryCache localCache,
IDistributedCache distributedCache) : IRequestHandler<CreateBlogPostCommand, Result<Guid>>
IBlogPostRepository repo,
IMemoryCache localCache,
IDistributedCache distributedCache) : IRequestHandler<CreateBlogPostCommand, Result<Guid>>
{
public async Task<Result<Guid>> Handle(CreateBlogPostCommand request, CancellationToken ct)
{
try
{
var post = BlogPost.Create(request.Title, request.Content, request.Author);
await repo.AddAsync(post, ct);
localCache.Remove("blog:all");
_ = distributedCache.RemoveAsync("blog:all", ct);
return Result.Ok<Guid>(post.Id);
}
catch (Exception ex)
{
return Result.Fail<Guid>(ex.Message);
}
}
public async Task<Result<Guid>> Handle(CreateBlogPostCommand request, CancellationToken ct)
{
try
{
var post = BlogPost.Create(request.Title, request.Content, request.Author);
await repo.AddAsync(post, ct);
localCache.Remove("blog:all");
_ = distributedCache.RemoveAsync("blog:all", ct);

Copilot AI Apr 18, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

distributedCache.RemoveAsync("blog:all", ct) is invoked fire-and-forget (_ = ...) and not awaited. This can leave Redis cache invalidation racing with the response (stale reads right after create) and can also drop exceptions from the cache backend. Consider awaiting the call (as Edit/Delete handlers do) or explicitly handling/logging failures if you intentionally want it to be best-effort.

Suggested change
_ = distributedCache.RemoveAsync("blog:all", ct);
await distributedCache.RemoveAsync("blog:all", ct);

Copilot uses AI. Check for mistakes.
return Result.Ok<Guid>(post.Id);
}
catch (Exception ex)
{
return Result.Fail<Guid>(ex.Message);
}
}
}
3 changes: 0 additions & 3 deletions src/Web/Features/BlogPosts/Delete/DeleteBlogPostCommand.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
using MediatR;
using Domain.Abstractions;

namespace MyBlog.Web.Features.BlogPosts.Delete;

public sealed record DeleteBlogPostCommand(Guid Id) : IRequest<Result>;
57 changes: 25 additions & 32 deletions src/Web/Features/BlogPosts/Delete/DeleteBlogPostHandler.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,30 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using MyBlog.Domain.Interfaces;
using Domain.Abstractions;

namespace MyBlog.Web.Features.BlogPosts.Delete;

public sealed class DeleteBlogPostHandler(
IBlogPostRepository repo,
IMemoryCache localCache,
IDistributedCache distributedCache) : IRequestHandler<DeleteBlogPostCommand, Result>
IBlogPostRepository repo,
IMemoryCache localCache,
IDistributedCache distributedCache) : IRequestHandler<DeleteBlogPostCommand, Result>
{
public async Task<Result> Handle(DeleteBlogPostCommand request, CancellationToken ct)
{
try
{
await repo.DeleteAsync(request.Id, ct);
localCache.Remove("blog:all");
localCache.Remove($"blog:{request.Id}");
await distributedCache.RemoveAsync("blog:all", ct);
await distributedCache.RemoveAsync($"blog:{request.Id}", ct);
return Result.Ok();
}
catch (DbUpdateConcurrencyException)
{
return Result.Fail(
"This post was modified by another user. Please reload and try again.",
ResultErrorCode.Concurrency);
}
catch (Exception ex)
{
return Result.Fail(ex.Message);
}
}
public async Task<Result> Handle(DeleteBlogPostCommand request, CancellationToken ct)
{
try
{
await repo.DeleteAsync(request.Id, ct);
localCache.Remove("blog:all");
localCache.Remove($"blog:{request.Id}");
await distributedCache.RemoveAsync("blog:all", ct);
await distributedCache.RemoveAsync($"blog:{request.Id}", ct);
return Result.Ok();
}
catch (DbUpdateConcurrencyException)
{
return Result.Fail(
"This post was modified by another user. Please reload and try again.",
ResultErrorCode.Concurrency);
}
catch (Exception ex)
{
return Result.Fail(ex.Message);
}
}
}
3 changes: 0 additions & 3 deletions src/Web/Features/BlogPosts/Edit/EditBlogPostCommand.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
using MediatR;
using Domain.Abstractions;

namespace MyBlog.Web.Features.BlogPosts.Edit;

public sealed record EditBlogPostCommand(Guid Id, string Title, string Content) : IRequest<Result>;
Loading
Loading