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