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:
parent
6cad42dbac
commit
6b58dfa4e4
9
backend/ClaudeTest.Domain/Common/BaseModel.cs
Normal file
9
backend/ClaudeTest.Domain/Common/BaseModel.cs
Normal 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; }
|
||||||
|
}
|
||||||
@ -5,6 +5,11 @@
|
|||||||
<ProjectReference Include="..\ClaudeTest.Domain\ClaudeTest.Domain.csproj" />
|
<ProjectReference Include="..\ClaudeTest.Domain\ClaudeTest.Domain.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.*" />
|
||||||
|
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.*" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
|||||||
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user