| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using OzonRepositories.Context; |
| | | 3 | | |
| | | 4 | | namespace Services.LabelServices; |
| | | 5 | | |
| | | 6 | | public class OrderScanitStore : IOrderScanitStore |
| | | 7 | | { |
| | | 8 | | private readonly IDbContextFactory<ApplicationDbContext> _dbFactory; |
| | | 9 | | |
| | 3 | 10 | | public OrderScanitStore(IDbContextFactory<ApplicationDbContext> dbFactory) |
| | | 11 | | { |
| | 3 | 12 | | _dbFactory = dbFactory; |
| | 3 | 13 | | } |
| | | 14 | | |
| | | 15 | | public async Task<int> SaveAsync(IReadOnlyDictionary<string, string> scanitByPosting, CancellationToken ct = default |
| | | 16 | | { |
| | 4 | 17 | | if (scanitByPosting.Count == 0) |
| | | 18 | | { |
| | 1 | 19 | | return 0; |
| | | 20 | | } |
| | | 21 | | |
| | 3 | 22 | | await using var db = await _dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false); |
| | | 23 | | |
| | | 24 | | // Контекст настроен с EnableRetryOnFailure: пользовательскую транзакцию нужно выполнять |
| | | 25 | | // внутри стратегии выполнения, иначе EF откажется её открывать. |
| | 3 | 26 | | var strategy = db.Database.CreateExecutionStrategy(); |
| | 3 | 27 | | return await strategy.ExecuteAsync(async () => |
| | 3 | 28 | | { |
| | 3 | 29 | | await using var transaction = await db.Database.BeginTransactionAsync(ct).ConfigureAwait(false); |
| | 3 | 30 | | |
| | 3 | 31 | | var updated = 0; |
| | 14 | 32 | | foreach (var (posting, scanit) in scanitByPosting) |
| | 3 | 33 | | { |
| | 4 | 34 | | var childPrefix = posting + "/"; |
| | 4 | 35 | | updated += await db.Orders |
| | 4 | 36 | | .Where(o => o.ShipmentNumber != null |
| | 4 | 37 | | && (o.ShipmentNumber == posting || o.ShipmentNumber.StartsWith(childPrefix)) |
| | 4 | 38 | | && o.Scanit != scanit) |
| | 4 | 39 | | .ExecuteUpdateAsync(s => s.SetProperty(o => o.Scanit, scanit), ct) |
| | 4 | 40 | | .ConfigureAwait(false); |
| | 3 | 41 | | } |
| | 3 | 42 | | |
| | 3 | 43 | | await transaction.CommitAsync(ct).ConfigureAwait(false); |
| | 3 | 44 | | return updated; |
| | 3 | 45 | | }).ConfigureAwait(false); |
| | 4 | 46 | | } |
| | | 47 | | } |