| | | 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 | | ) |
| | 184 | 17 | | : DbContext(options) |
| | | 18 | | { |
| | 186 | 19 | | private readonly ILogger<ApplicationDbContext> _logger = logger; |
| | 186 | 20 | | private readonly IApplicationSaveChangesPipeline _saveChangesPipeline = |
| | 186 | 21 | | saveChangesPipeline ?? throw new ArgumentNullException(nameof(saveChangesPipeline)); |
| | 184 | 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 = 19001, |
| | | 42 | | Level = LogLevel.Warning, |
| | | 43 | | Message = "Optimistic concurrency conflict detected while saving {EntryCount} tracked entity entries.")] |
| | | 44 | | private static partial void LogOptimisticConcurrencyConflict( |
| | | 45 | | ILogger logger, |
| | | 46 | | int entryCount, |
| | | 47 | | Exception exception); |
| | | 48 | | |
| | | 49 | | /// <inheritdoc /> |
| | | 50 | | protected override void OnModelCreating(ModelBuilder modelBuilder) |
| | | 51 | | { |
| | 10 | 52 | | ArgumentNullException.ThrowIfNull(modelBuilder); |
| | | 53 | | |
| | 10 | 54 | | _ = modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly); |
| | 10 | 55 | | ConfigureDataEntityDefaults(modelBuilder); |
| | 10 | 56 | | ConfigureTimestampDefaults(modelBuilder); |
| | | 57 | | |
| | 10 | 58 | | base.OnModelCreating(modelBuilder); |
| | 10 | 59 | | } |
| | | 60 | | |
| | | 61 | | /// <inheritdoc /> |
| | | 62 | | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) |
| | | 63 | | { |
| | 184 | 64 | | ArgumentNullException.ThrowIfNull(optionsBuilder); |
| | | 65 | | |
| | 184 | 66 | | ApplicationSaveChangesInterceptor interceptor = |
| | 184 | 67 | | _configuredSaveChangesInterceptor ?? new ApplicationSaveChangesInterceptor(_saveChangesPipeline); |
| | | 68 | | |
| | 184 | 69 | | _ = optionsBuilder.AddInterceptors(interceptor); |
| | | 70 | | |
| | 184 | 71 | | base.OnConfiguring(optionsBuilder); |
| | 184 | 72 | | } |
| | | 73 | | |
| | | 74 | | public bool HasUnsavedChanges() |
| | | 75 | | { |
| | 20 | 76 | | return ChangeTracker.HasChanges(); |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | public override int SaveChanges() |
| | | 80 | | { |
| | 20 | 81 | | return SaveChanges(acceptAllChangesOnSuccess: true); |
| | | 82 | | } |
| | | 83 | | |
| | | 84 | | public override int SaveChanges(bool acceptAllChangesOnSuccess = true) |
| | | 85 | | { |
| | 20 | 86 | | return SaveChangesWithConcurrencyHandling( |
| | 40 | 87 | | () => base.SaveChanges(acceptAllChangesOnSuccess)); |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) |
| | | 91 | | { |
| | 140 | 92 | | return SaveChangesAsync( |
| | 140 | 93 | | acceptAllChangesOnSuccess: true, |
| | 140 | 94 | | cancellationToken); |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | public override Task<int> SaveChangesAsync( |
| | | 98 | | bool acceptAllChangesOnSuccess, |
| | | 99 | | CancellationToken cancellationToken = default) |
| | | 100 | | { |
| | 140 | 101 | | return SaveChangesWithConcurrencyHandlingAsync( |
| | 280 | 102 | | () => base.SaveChangesAsync( |
| | 280 | 103 | | acceptAllChangesOnSuccess, |
| | 280 | 104 | | cancellationToken)); |
| | | 105 | | } |
| | | 106 | | |
| | | 107 | | private static bool IsUtcTimestampProperty(string propertyName) |
| | | 108 | | { |
| | 130 | 109 | | return propertyName.EndsWith("Utc", StringComparison.Ordinal); |
| | | 110 | | } |
| | | 111 | | |
| | | 112 | | private static void ConfigureDataEntityDefaults(ModelBuilder modelBuilder) |
| | | 113 | | { |
| | 120 | 114 | | foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes()) |
| | | 115 | | { |
| | 50 | 116 | | if (!typeof(DataEntity).IsAssignableFrom(entityType.ClrType)) |
| | | 117 | | { |
| | | 118 | | continue; |
| | | 119 | | } |
| | | 120 | | |
| | 50 | 121 | | _ = modelBuilder.Entity(entityType.ClrType) |
| | 50 | 122 | | .Property<string>(nameof(DataEntity.ConcurrencyStamp)) |
| | 50 | 123 | | .HasMaxLength(64) |
| | 50 | 124 | | .IsRequired() |
| | 50 | 125 | | .IsConcurrencyToken(); |
| | | 126 | | } |
| | 10 | 127 | | } |
| | | 128 | | |
| | | 129 | | private static void ConfigureTimestampDefaults(ModelBuilder modelBuilder) |
| | | 130 | | { |
| | 120 | 131 | | foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes()) |
| | | 132 | | { |
| | 1700 | 133 | | foreach (IMutableProperty property in entityType.GetProperties()) |
| | | 134 | | { |
| | 800 | 135 | | Type propertyType = Nullable.GetUnderlyingType(property.ClrType) |
| | 800 | 136 | | ?? property.ClrType; |
| | | 137 | | |
| | 800 | 138 | | if ((propertyType == typeof(DateTime) || propertyType == typeof(DateTimeOffset)) && |
| | 800 | 139 | | IsUtcTimestampProperty(property.Name)) |
| | | 140 | | { |
| | 130 | 141 | | property.SetPrecision(PersistenceTimestamp.Precision); |
| | | 142 | | } |
| | | 143 | | } |
| | | 144 | | } |
| | 10 | 145 | | } |
| | | 146 | | |
| | | 147 | | private int SaveChangesWithConcurrencyHandling(Func<int> saveChanges) |
| | | 148 | | { |
| | | 149 | | try |
| | | 150 | | { |
| | 20 | 151 | | return saveChanges(); |
| | | 152 | | } |
| | 2 | 153 | | catch (DbUpdateConcurrencyException exception) |
| | | 154 | | { |
| | 2 | 155 | | LogOptimisticConcurrencyConflict(_logger, exception.Entries.Count, exception); |
| | 2 | 156 | | throw; |
| | | 157 | | } |
| | 18 | 158 | | } |
| | | 159 | | |
| | | 160 | | private async Task<int> SaveChangesWithConcurrencyHandlingAsync(Func<Task<int>> saveChanges) |
| | | 161 | | { |
| | | 162 | | try |
| | | 163 | | { |
| | 140 | 164 | | return await saveChanges().ConfigureAwait(false); |
| | | 165 | | } |
| | 2 | 166 | | catch (DbUpdateConcurrencyException exception) |
| | | 167 | | { |
| | 2 | 168 | | LogOptimisticConcurrencyConflict(_logger, exception.Entries.Count, exception); |
| | 2 | 169 | | throw; |
| | | 170 | | } |
| | 134 | 171 | | } |
| | | 172 | | } |