ApplicationDbContext.cs 6.7 KB

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