Fix concurrent

This commit is contained in:
2025-08-14 18:31:44 +07:00
parent 0a2b7aa335
commit cfb04e9dc9
4 changed files with 71 additions and 74 deletions

View File

@@ -1,4 +1,3 @@
using System.Data;
using Managing.Application.Abstractions.Repositories;
using Managing.Domain.Users;
using Microsoft.EntityFrameworkCore;
@@ -14,33 +13,13 @@ public class PostgreSqlUserRepository : IUserRepository
_context = context;
}
/// <summary>
/// Ensures the database connection is open before executing queries
/// </summary>
private async Task EnsureConnectionOpenAsync()
{
if (_context.Database.GetDbConnection().State != ConnectionState.Open)
{
await _context.Database.OpenConnectionAsync();
}
}
/// <summary>
/// Safely closes the database connection if it was opened by us
/// </summary>
private async Task SafeCloseConnectionAsync()
{
if (_context.Database.GetDbConnection().State == ConnectionState.Open)
{
await _context.Database.CloseConnectionAsync();
}
}
public async Task<User> GetUserByAgentNameAsync(string agentName)
{
try
{
await EnsureConnectionOpenAsync();
await PostgreSqlConnectionHelper.EnsureConnectionOpenAsync(_context);
var userEntity = await _context.Users
.AsNoTracking()
@@ -49,11 +28,10 @@ public class PostgreSqlUserRepository : IUserRepository
return PostgreSqlMappers.Map(userEntity);
}
catch (Exception)
finally
{
// If there's an error, try to reset the connection
await SafeCloseConnectionAsync();
throw;
// Always ensure the connection is closed after the operation
await PostgreSqlConnectionHelper.SafeCloseConnectionAsync(_context);
}
}
@@ -61,7 +39,7 @@ public class PostgreSqlUserRepository : IUserRepository
{
try
{
await EnsureConnectionOpenAsync();
await PostgreSqlConnectionHelper.EnsureConnectionOpenAsync(_context);
var userEntity = await _context.Users
.AsNoTracking()
@@ -70,11 +48,10 @@ public class PostgreSqlUserRepository : IUserRepository
return PostgreSqlMappers.Map(userEntity);
}
catch (Exception)
finally
{
// If there's an error, try to reset the connection
await SafeCloseConnectionAsync();
throw;
// Always ensure the connection is closed after the operation
await PostgreSqlConnectionHelper.SafeCloseConnectionAsync(_context);
}
}
@@ -82,7 +59,7 @@ public class PostgreSqlUserRepository : IUserRepository
{
try
{
await EnsureConnectionOpenAsync();
await PostgreSqlConnectionHelper.EnsureConnectionOpenAsync(_context);
var userEntities = await _context.Users
.AsNoTracking()
@@ -91,11 +68,10 @@ public class PostgreSqlUserRepository : IUserRepository
return userEntities.Select(PostgreSqlMappers.Map);
}
catch (Exception)
finally
{
// If there's an error, try to reset the connection
await SafeCloseConnectionAsync();
throw;
// Always ensure the connection is closed after the operation
await PostgreSqlConnectionHelper.SafeCloseConnectionAsync(_context);
}
}