- 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>
43 lines
1.1 KiB
C#
43 lines
1.1 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|
|
}
|