46 lines
1.3 KiB
C#
46 lines
1.3 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using MyNewProjectName.Domain.Common;
|
|
using MyNewProjectName.Domain.Entities;
|
|
using System.Reflection;
|
|
|
|
namespace MyNewProjectName.Infrastructure.Persistence.Context;
|
|
|
|
/// <summary>
|
|
/// Application database context
|
|
/// </summary>
|
|
public class ApplicationDbContext : DbContext
|
|
{
|
|
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
|
|
: base(options)
|
|
{
|
|
}
|
|
|
|
public DbSet<SampleEntity> Samples => Set<SampleEntity>();
|
|
|
|
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
foreach (var entry in ChangeTracker.Entries<AuditableEntity>())
|
|
{
|
|
switch (entry.State)
|
|
{
|
|
case EntityState.Added:
|
|
entry.Entity.CreatedAt = DateTime.UtcNow;
|
|
break;
|
|
|
|
case EntityState.Modified:
|
|
entry.Entity.UpdatedAt = DateTime.UtcNow;
|
|
break;
|
|
}
|
|
}
|
|
|
|
return await base.SaveChangesAsync(cancellationToken);
|
|
}
|
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
|
{
|
|
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
|
|
|
|
base.OnModelCreating(modelBuilder);
|
|
}
|
|
}
|