Add BaseModel and AppDbContext with auto timestamps

- BaseModel in Domain.Common with Id, Created, Updated, Deleted fields
- AppDbContext in Infrastructure.Persistence overrides SaveChanges/Async
  to automatically set Created/Updated via ChangeTracker
- Added EF Core 8 and Pomelo.EntityFrameworkCore.MySql 8 packages

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Martin Švrčina 2026-03-17 00:28:31 +01:00
parent 6cad42dbac
commit 6b58dfa4e4
3 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,9 @@
namespace ClaudeTest.Domain.Common;
public abstract class BaseModel
{
public int Id { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public DateTime? Deleted { get; set; }
}

View File

@ -5,6 +5,11 @@
<ProjectReference Include="..\ClaudeTest.Domain\ClaudeTest.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.*" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.*" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>

View File

@ -0,0 +1,42 @@
using ClaudeTest.Domain.Common;
using Microsoft.EntityFrameworkCore;
namespace ClaudeTest.Infrastructure.Persistence;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public override int SaveChanges()
{
SetTimestamps();
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
SetTimestamps();
return base.SaveChangesAsync(cancellationToken);
}
private void SetTimestamps()
{
var entries = ChangeTracker.Entries<BaseModel>();
foreach (var entry in entries)
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.Created = DateTime.UtcNow;
entry.Entity.Updated = DateTime.UtcNow;
break;
case EntityState.Modified:
entry.Entity.Updated = DateTime.UtcNow;
break;
}
}
}
}