From 4292e9e02f4a14fd83af64defa44fea4672735e2 Mon Sep 17 00:00:00 2001 From: cryptooda Date: Fri, 15 Aug 2025 21:09:26 +0700 Subject: [PATCH] fix save agent summary --- .../PostgreSql/AgentSummaryRepository.cs | 100 ++++++++++++------ 1 file changed, 68 insertions(+), 32 deletions(-) diff --git a/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs b/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs index e87aa00..b75b909 100644 --- a/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs +++ b/src/Managing.Infrastructure.Database/PostgreSql/AgentSummaryRepository.cs @@ -79,42 +79,78 @@ public class AgentSummaryRepository : IAgentSummaryRepository public async Task SaveOrUpdateAsync(AgentSummary agentSummary) { - // Ensure the User entity exists and is saved - if (agentSummary.User != null) + // Use the execution strategy to handle retries and transactions + var strategy = _context.Database.CreateExecutionStrategy(); + await strategy.ExecuteAsync(async () => { - var existingUser = await _context.Users - .FirstOrDefaultAsync(u => u.Id == agentSummary.UserId); - - if (existingUser == null) + using var transaction = await _context.Database.BeginTransactionAsync(); + try { - // User doesn't exist, save it first - var userEntity = PostgreSqlMappers.Map(agentSummary.User); - await _context.Users.AddAsync(userEntity); - await _context.SaveChangesAsync(); + // Ensure the User entity exists and is saved + if (agentSummary.User != null) + { + var existingUser = await _context.Users + .AsNoTracking() + .FirstOrDefaultAsync(u => u.Id == agentSummary.UserId); - _logger.LogInformation("User created for AgentSummary with ID {UserId}", agentSummary.UserId); + if (existingUser == null) + { + // User doesn't exist, save it first + var userEntity = PostgreSqlMappers.Map(agentSummary.User); + userEntity.Id = agentSummary.UserId; // Ensure the ID is set + await _context.Users.AddAsync(userEntity); + await _context.SaveChangesAsync(); + + _logger.LogInformation("User created for AgentSummary with ID {UserId}", agentSummary.UserId); + } + } + + // Check if AgentSummary exists (using AsNoTracking to avoid tracking conflicts) + var existing = await _context.AgentSummaries + .AsNoTracking() + .FirstOrDefaultAsync(a => a.UserId == agentSummary.UserId); + + if (existing == null) + { + // Insert new AgentSummary + var entity = MapToEntity(agentSummary); + entity.CreatedAt = DateTime.UtcNow; + entity.UpdatedAt = DateTime.UtcNow; + + await _context.AgentSummaries.AddAsync(entity); + await _context.SaveChangesAsync(); + + _logger.LogInformation("AgentSummary inserted for user {UserId} with agent name {AgentName}", + agentSummary.UserId, agentSummary.AgentName); + } + else + { + // Update existing record - attach and modify the entity + var entityToUpdate = MapToEntity(agentSummary); + entityToUpdate.Id = existing.Id; // Preserve the existing ID + entityToUpdate.CreatedAt = existing.CreatedAt; // Preserve creation date + entityToUpdate.UpdatedAt = DateTime.UtcNow; + + // Attach the entity and mark it as modified + _context.AgentSummaries.Attach(entityToUpdate); + _context.Entry(entityToUpdate).State = EntityState.Modified; + + await _context.SaveChangesAsync(); + + _logger.LogInformation("AgentSummary updated for user {UserId} with agent name {AgentName}", + agentSummary.UserId, agentSummary.AgentName); + } + + await transaction.CommitAsync(); } - } - - var existing = await _context.AgentSummaries - .FirstOrDefaultAsync(a => a.UserId == agentSummary.UserId); - - if (existing == null) - { - await InsertAsync(agentSummary); - } - else - { - // Update existing record - modify the tracked entity directly - MapToEntity(agentSummary, existing); - existing.UpdatedAt = DateTime.UtcNow; - - // No need to call Update() since the entity is already being tracked - await _context.SaveChangesAsync(); - - _logger.LogInformation("AgentSummary updated for user {UserId} with agent name {AgentName}", - agentSummary.UserId, agentSummary.AgentName); - } + catch (Exception ex) + { + await transaction.RollbackAsync(); + _logger.LogError(ex, "Error saving/updating AgentSummary for user {UserId} with agent name {AgentName}", + agentSummary.UserId, agentSummary.AgentName); + throw; + } + }); } public async Task<(IEnumerable Results, int TotalCount)> GetPaginatedAsync(