| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using Microsoft.EntityFrameworkCore.Metadata; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using ProjectTemplate.Infrastructure.Data.Entities; |
| | | 5 | | |
| | | 6 | | namespace ProjectTemplate.Infrastructure.Data; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Represents the EF Core database context for the ProjectTemplate application. |
| | | 10 | | /// </summary> |
| | | 11 | | public sealed partial class ApplicationDbContext( |
| | | 12 | | DbContextOptions<ApplicationDbContext> options, |
| | | 13 | | ILogger<ApplicationDbContext> logger, |
| | | 14 | | ApplicationSaveChangesInterceptor saveChangesInterceptor |
| | | 15 | | ) |
| | 117 | 16 | | : DbContext(options) |
| | | 17 | | { |
| | 118 | 18 | | private readonly ILogger<ApplicationDbContext> _logger = logger; |
| | 118 | 19 | | private readonly ApplicationSaveChangesInterceptor _saveChangesInterceptor = |
| | 118 | 20 | | saveChangesInterceptor ?? throw new ArgumentNullException(nameof(saveChangesInterceptor)); |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Gets the audit records for the application. |
| | | 24 | | /// </summary> |
| | 127 | 25 | | public DbSet<AuditRecord> AuditRecords => Set<AuditRecord>(); |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Gets the durable, minimized audit-completion outbox entries. |
| | | 29 | | /// </summary> |
| | | 30 | | public DbSet<ApplicationAuditCompletionOutboxEntry> ApplicationAuditCompletionOutboxEntries => |
| | 76 | 31 | | Set<ApplicationAuditCompletionOutboxEntry>(); |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Gets the external login account links for the application. |
| | | 35 | | /// </summary> |
| | 89 | 36 | | public DbSet<ExternalLoginAccount> ExternalLoginAccounts => Set<ExternalLoginAccount>(); |
| | | 37 | | |
| | | 38 | | [LoggerMessage( |
| | | 39 | | EventId = 19001, |
| | | 40 | | Level = LogLevel.Warning, |
| | | 41 | | Message = "Optimistic concurrency conflict detected while saving {EntryCount} tracked entity entries.")] |
| | | 42 | | private static partial void LogOptimisticConcurrencyConflict( |
| | | 43 | | ILogger logger, |
| | | 44 | | int entryCount, |
| | | 45 | | Exception exception); |
| | | 46 | | |
| | | 47 | | /// <inheritdoc /> |
| | | 48 | | protected override void OnModelCreating(ModelBuilder modelBuilder) |
| | | 49 | | { |
| | 5 | 50 | | ArgumentNullException.ThrowIfNull(modelBuilder); |
| | | 51 | | |
| | 5 | 52 | | _ = modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly); |
| | 5 | 53 | | ConfigureDataEntityDefaults(modelBuilder); |
| | 5 | 54 | | ConfigureTimestampDefaults(modelBuilder); |
| | | 55 | | |
| | 5 | 56 | | base.OnModelCreating(modelBuilder); |
| | 5 | 57 | | } |
| | | 58 | | |
| | | 59 | | /// <inheritdoc /> |
| | | 60 | | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) |
| | | 61 | | { |
| | 116 | 62 | | ArgumentNullException.ThrowIfNull(optionsBuilder); |
| | | 63 | | |
| | 116 | 64 | | _ = optionsBuilder.AddInterceptors(_saveChangesInterceptor); |
| | | 65 | | |
| | 116 | 66 | | base.OnConfiguring(optionsBuilder); |
| | 116 | 67 | | } |
| | | 68 | | |
| | | 69 | | public bool HasUnsavedChanges() |
| | | 70 | | { |
| | 13 | 71 | | return ChangeTracker.HasChanges(); |
| | | 72 | | } |
| | | 73 | | |
| | | 74 | | public override int SaveChanges() |
| | | 75 | | { |
| | 11 | 76 | | return SaveChanges(acceptAllChangesOnSuccess: true); |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | public override int SaveChanges(bool acceptAllChangesOnSuccess = true) |
| | | 80 | | { |
| | 11 | 81 | | return SaveChangesWithConcurrencyHandling( |
| | 11 | 82 | | () => base.SaveChanges(acceptAllChangesOnSuccess)); |
| | | 83 | | } |
| | | 84 | | |
| | | 85 | | public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) |
| | | 86 | | { |
| | 93 | 87 | | return SaveChangesAsync( |
| | 93 | 88 | | acceptAllChangesOnSuccess: true, |
| | 93 | 89 | | cancellationToken); |
| | | 90 | | } |
| | | 91 | | |
| | | 92 | | public override Task<int> SaveChangesAsync( |
| | | 93 | | bool acceptAllChangesOnSuccess, |
| | | 94 | | CancellationToken cancellationToken = default) |
| | | 95 | | { |
| | 93 | 96 | | return SaveChangesWithConcurrencyHandlingAsync( |
| | 93 | 97 | | () => base.SaveChangesAsync( |
| | 93 | 98 | | acceptAllChangesOnSuccess, |
| | 93 | 99 | | cancellationToken)); |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | private static bool IsUtcTimestampProperty(string propertyName) |
| | | 103 | | { |
| | 65 | 104 | | return propertyName.EndsWith("Utc", StringComparison.Ordinal); |
| | | 105 | | } |
| | | 106 | | |
| | | 107 | | private static void ConfigureDataEntityDefaults(ModelBuilder modelBuilder) |
| | | 108 | | { |
| | 60 | 109 | | foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes()) |
| | | 110 | | { |
| | 25 | 111 | | if (!typeof(DataEntity).IsAssignableFrom(entityType.ClrType)) |
| | | 112 | | { |
| | | 113 | | continue; |
| | | 114 | | } |
| | | 115 | | |
| | 25 | 116 | | _ = modelBuilder.Entity(entityType.ClrType) |
| | 25 | 117 | | .Property<string>(nameof(DataEntity.ConcurrencyStamp)) |
| | 25 | 118 | | .HasMaxLength(64) |
| | 25 | 119 | | .IsRequired() |
| | 25 | 120 | | .IsConcurrencyToken(); |
| | | 121 | | } |
| | 5 | 122 | | } |
| | | 123 | | |
| | | 124 | | private static void ConfigureTimestampDefaults(ModelBuilder modelBuilder) |
| | | 125 | | { |
| | 60 | 126 | | foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes()) |
| | | 127 | | { |
| | 850 | 128 | | foreach (IMutableProperty property in entityType.GetProperties()) |
| | | 129 | | { |
| | 400 | 130 | | Type propertyType = Nullable.GetUnderlyingType(property.ClrType) |
| | 400 | 131 | | ?? property.ClrType; |
| | | 132 | | |
| | 400 | 133 | | if ((propertyType == typeof(DateTime) || propertyType == typeof(DateTimeOffset)) && |
| | 400 | 134 | | IsUtcTimestampProperty(property.Name)) |
| | | 135 | | { |
| | 65 | 136 | | property.SetPrecision(PersistenceTimestamp.Precision); |
| | | 137 | | } |
| | | 138 | | } |
| | | 139 | | } |
| | 5 | 140 | | } |
| | | 141 | | |
| | | 142 | | private int SaveChangesWithConcurrencyHandling(Func<int> saveChanges) |
| | | 143 | | { |
| | | 144 | | try |
| | | 145 | | { |
| | 11 | 146 | | return saveChanges(); |
| | | 147 | | } |
| | 1 | 148 | | catch (DbUpdateConcurrencyException exception) |
| | | 149 | | { |
| | 1 | 150 | | LogOptimisticConcurrencyConflict(_logger, exception.Entries.Count, exception); |
| | 1 | 151 | | throw; |
| | | 152 | | } |
| | 10 | 153 | | } |
| | | 154 | | |
| | | 155 | | private async Task<int> SaveChangesWithConcurrencyHandlingAsync(Func<Task<int>> saveChanges) |
| | | 156 | | { |
| | | 157 | | try |
| | | 158 | | { |
| | 93 | 159 | | return await saveChanges().ConfigureAwait(false); |
| | | 160 | | } |
| | 1 | 161 | | catch (DbUpdateConcurrencyException exception) |
| | | 162 | | { |
| | 1 | 163 | | LogOptimisticConcurrencyConflict(_logger, exception.Entries.Count, exception); |
| | 1 | 164 | | throw; |
| | | 165 | | } |
| | 90 | 166 | | } |
| | | 167 | | } |