|
1 | 1 | using Microsoft.EntityFrameworkCore; |
2 | 2 | using Shared.General; |
3 | 3 | using System; |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
4 | 6 |
|
5 | 7 | namespace TestHosts.Database.PataPawa |
6 | 8 | { |
@@ -59,5 +61,59 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { |
59 | 61 |
|
60 | 62 | base.OnModelCreating(modelBuilder); |
61 | 63 | } |
| 64 | + |
| 65 | + private async Task SetDbInSimpleMode(CancellationToken cancellationToken) |
| 66 | + { |
| 67 | + var dbName = this.Database.GetDbConnection().Database; |
| 68 | + |
| 69 | + var connection = this.Database.GetDbConnection(); |
| 70 | + if (connection.State != System.Data.ConnectionState.Open) |
| 71 | + await connection.OpenAsync(cancellationToken); |
| 72 | + |
| 73 | + // 1. Check current recovery model |
| 74 | + await using var checkCommand = connection.CreateCommand(); |
| 75 | + checkCommand.CommandText = @" |
| 76 | +SELECT recovery_model_desc |
| 77 | +FROM sys.databases |
| 78 | +WHERE name = @dbName; |
| 79 | +"; |
| 80 | + var param = checkCommand.CreateParameter(); |
| 81 | + param.ParameterName = "@dbName"; |
| 82 | + param.Value = dbName; |
| 83 | + checkCommand.Parameters.Add(param); |
| 84 | + |
| 85 | + var result = await checkCommand.ExecuteScalarAsync(cancellationToken); |
| 86 | + var currentRecoveryModel = result?.ToString(); |
| 87 | + |
| 88 | + if (currentRecoveryModel != "SIMPLE") |
| 89 | + { |
| 90 | + // 2. Alter database outside transaction |
| 91 | + await using var alterCommand = connection.CreateCommand(); |
| 92 | + alterCommand.CommandText = $@" |
| 93 | +ALTER DATABASE [{dbName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; |
| 94 | +ALTER DATABASE [{dbName}] SET RECOVERY SIMPLE; |
| 95 | +ALTER DATABASE [{dbName}] SET MULTI_USER; |
| 96 | +"; |
| 97 | + // Execute outside EF transaction |
| 98 | + await alterCommand.ExecuteNonQueryAsync(cancellationToken); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + public virtual async Task MigrateAsync(CancellationToken cancellationToken) |
| 103 | + { |
| 104 | + if (this.Database.IsSqlServer()) |
| 105 | + { |
| 106 | + try |
| 107 | + { |
| 108 | + await this.Database.MigrateAsync(cancellationToken); |
| 109 | + await this.SetDbInSimpleMode(cancellationToken); |
| 110 | + } |
| 111 | + catch (Exception ex) |
| 112 | + { |
| 113 | + // Log the exception or handle it as needed |
| 114 | + throw new InvalidOperationException("An error occurred while migrating the database.", ex); |
| 115 | + } |
| 116 | + } |
| 117 | + } |
62 | 118 | } |
63 | 119 | } |
0 commit comments