ApplicationDbContext.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #nullable disable
  2. using AipGateway.API.Domain.Entities;
  3. using AipGateway.API.Domain.IServices.IUtilities;
  4. using AipGateway.API.Infrastructure.Configurations;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.Logging;
  7. using System.Data;
  8. namespace AipGateway.API.Infrastructure.Persistence
  9. {
  10. public class ApplicationDbContext : DbContext
  11. {
  12. private readonly ILogger<ApplicationDbContext> _log;
  13. private readonly IDomainEventDispatcher _dispatcher;
  14. private readonly ConnectionInfo _connectionInfo;
  15. public ApplicationDbContext(ILogger<ApplicationDbContext> logger, DbContextOptions<ApplicationDbContext> options, ConnectionInfo connectionInfo) : base(options)
  16. {
  17. _log = logger;
  18. _connectionInfo = connectionInfo;
  19. }
  20. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  21. {
  22. optionsBuilder.UseSqlServer(_connectionInfo.ConnectionString, b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName));
  23. }
  24. protected override void OnModelCreating(ModelBuilder builder)
  25. {
  26. #if false
  27. //ApplicationDbContextSeed.SeedSampleDataAsync(modelBuilder); ==> 테스트 데이터 넣을 경우
  28. foreach (var entityType in builder.Model.GetEntityTypes())
  29. {
  30. //get first property of entity with DatabaseGeneratedAttribute = DatabaseGeneratedOption.Identity
  31. var idProp = entityType.GetProperties()
  32. .FirstOrDefault(x => x.PropertyInfo != null
  33. && x.PropertyInfo.GetCustomAttribute<DatabaseGeneratedAttribute>()
  34. ?.DatabaseGeneratedOption == DatabaseGeneratedOption.Identity);
  35. //if it exists, set it to identity
  36. if (idProp != null)
  37. {
  38. builder.Entity(entityType.ClrType)
  39. .Property(idProp.Name)
  40. .ValueGeneratedOnAddOrUpdate()
  41. .UseIdentityColumn();
  42. }
  43. }
  44. #endif
  45. }
  46. public override int SaveChanges()
  47. {
  48. //var userID = _currentUserService.ID;
  49. //if (userID == 0)
  50. //{
  51. // return base.SaveChanges();
  52. //}
  53. foreach (var entry in ChangeTracker.Entries<BaseEntity>())
  54. {
  55. switch (entry.State)
  56. {
  57. case EntityState.Added:
  58. //entry.Entity.CreatedBy = userID;
  59. entry.Entity.CreatedAt = DateTime.UtcNow;
  60. entry.Entity.IsActive = true;
  61. entry.Entity.IsDeleted = false;
  62. break;
  63. case EntityState.Modified:
  64. //entry.Entity.ModifiedBy = userID;
  65. entry.Entity.ModifiedAt = DateTime.UtcNow;
  66. break;
  67. }
  68. }
  69. //foreach (var entry in ChangeTracker.Entries<AuditableEntity>())
  70. //{
  71. // switch (entry.State)
  72. // {
  73. // case EntityState.Added:
  74. // entry.Entity.CreatedBy = userID;
  75. // entry.Entity.CreatedAt = DateTime.UtcNow;
  76. // break;
  77. // case EntityState.Modified:
  78. // entry.Entity.ModifiedBy = userID;
  79. // entry.Entity.ModifiedAt = DateTime.UtcNow;
  80. // break;
  81. // }
  82. //}
  83. //foreach (var entry in ChangeTracker.Entries<UserRole>())
  84. //{
  85. // switch (entry.State)
  86. // {
  87. // case EntityState.Added:
  88. // entry.Entity.CreatedBy = userID;
  89. // entry.Entity.CreatedAt = DateTime.UtcNow;
  90. // break;
  91. // case EntityState.Modified:
  92. // entry.Entity.ModifiedBy = userID;
  93. // entry.Entity.ModifiedAt = DateTime.UtcNow;
  94. // break;
  95. // }
  96. //}
  97. PreSaveChanges().GetAwaiter().GetResult();
  98. var response = base.SaveChanges();
  99. PostSaveChanges().GetAwaiter().GetResult();
  100. return response;
  101. }
  102. private async Task PreSaveChanges()
  103. {
  104. await Task.CompletedTask;
  105. }
  106. private async Task PostSaveChanges()
  107. {
  108. await DispatchDomainEvents();
  109. }
  110. private async Task DispatchDomainEvents()
  111. {
  112. var domainEventEntities = ChangeTracker.Entries<IHasDomainEventEntity>()
  113. .Select(po => po.Entity)
  114. .Where(po => po.DomainEvents.Any())
  115. .ToArray();
  116. foreach (var entity in domainEventEntities)
  117. {
  118. while (entity.DomainEvents.TryTake(out IDomainEvent dev))
  119. await _dispatcher.Dispatch(dev);
  120. }
  121. }
  122. public IEnumerable<T> SqlQuery<T>(FormattableString sql)
  123. {
  124. try
  125. {
  126. return Database.SqlQuery<T>(sql);
  127. }
  128. catch (Exception ex)
  129. {
  130. _log.LogError("SqlQuery: {0}", sql.ToString());
  131. _log.LogError("SqlQuery: {0}", ex.Message);
  132. }
  133. return null;
  134. }
  135. public int ExecuteSql(FormattableString sql)
  136. {
  137. try
  138. {
  139. return Database.ExecuteSql(sql);
  140. }
  141. catch (Exception ex)
  142. {
  143. _log.LogError("ExecuteSql: {0}", sql.ToString());
  144. _log.LogError("ExecuteSql: {0}", ex.Message);
  145. }
  146. return -1;
  147. }
  148. public virtual DbSet<TbLinkedSystem> LinkedSystems { get; set; }
  149. public virtual DbSet<TbLinkedServer> LinkedServers { get; set; }
  150. public virtual DbSet<TbLinkedDecryptKey> LinkedDecryptKeys { get; set; }
  151. public virtual DbSet<TbLinkedApiKey> LinkedApiKeys { get; set; }
  152. public virtual DbSet<TbAipLabel> AipLabels { get; set; }
  153. public virtual DbSet<TbAipPolicy> AipPolicies { get; set; }
  154. public virtual DbSet<TbAipProtection> AipProtections { get; set; }
  155. public virtual DbSet<TbAipServer> AipServers { get; set; }
  156. public virtual DbSet<TbAipConfig> AipConfigs { get; set; }
  157. public virtual DbSet<TbAipFileJobLog> AipFileJobLogs { get; set; }
  158. public virtual DbSet<TbAipApiCallLog> AipApiCallLogs { get; set; }
  159. }
  160. }