Solved the database transcation error

This commit is contained in:
ashutosh.nehete 2025-07-21 18:39:34 +05:30
parent f9213b6040
commit 1fffde6d7f
2 changed files with 51 additions and 56 deletions

View File

@ -250,8 +250,6 @@ namespace Marco.Pms.Services.Service
public async Task<ApiResponse<object>> CreateExpenseAsync(CreateExpensesDto dto, Employee loggedInEmployee, Guid tenantId)
{
_logger.LogDebug("Starting CreateExpense for Project {ProjectId}", dto.ProjectId);
// The entire operation is wrapped in a transaction to ensure data consistency.
await using var transaction = await _context.Database.BeginTransactionAsync();
try
{
@ -301,7 +299,7 @@ namespace Marco.Pms.Services.Service
.Include(s => s.Status)
.Include(s => s.NextStatus)
.AsNoTracking()
.FirstOrDefaultAsync(es => es.StatusId == Draft && es.Status != null);
.Where(es => es.StatusId == Draft && es.Status != null).ToListAsync();
});
@ -329,11 +327,10 @@ namespace Marco.Pms.Services.Service
if (paidBy == null) validationErrors.Add("Paid by employee not found");
if (expenseType == null) validationErrors.Add("Expense Type not found.");
if (paymentMode == null) validationErrors.Add("Payment Mode not found.");
if (statusMapping == null) validationErrors.Add("Default status 'Draft' not found.");
if (!statusMapping.Any()) validationErrors.Add("Default status 'Draft' not found.");
if (validationErrors.Any())
{
await transaction.RollbackAsync();
var errorMessage = string.Join(" ", validationErrors);
_logger.LogWarning("Expense creation failed due to validation errors: {ValidationErrors}", errorMessage);
return ApiResponse<object>.ErrorResponse("Invalid input data.", errorMessage, 400);
@ -358,14 +355,13 @@ namespace Marco.Pms.Services.Service
// 5. Database Commit
await _context.SaveChangesAsync();
// 6. Transaction Commit
await transaction.CommitAsync();
var status = statusMapping.Select(sm => sm.Status).FirstOrDefault();
var nextStatus = statusMapping.Select(sm => sm.NextStatus).ToList();
var response = _mapper.Map<ExpenseList>(expense);
response.PaidBy = _mapper.Map<BasicEmployeeVM>(paidBy);
response.Project = _mapper.Map<ProjectInfoVM>(project);
response.Status = _mapper.Map<ExpensesStatusMasterVM>(statusMapping!.Status);
response.NextStatus = _mapper.Map<List<ExpensesStatusMasterVM>>(statusMapping!.NextStatus);
response.Status = _mapper.Map<ExpensesStatusMasterVM>(status);
response.NextStatus = _mapper.Map<List<ExpensesStatusMasterVM>>(nextStatus);
response.PaymentMode = _mapper.Map<PaymentModeMatserVM>(paymentMode);
response.ExpensesType = _mapper.Map<ExpensesTypeMasterVM>(expenseType);
@ -374,7 +370,6 @@ namespace Marco.Pms.Services.Service
}
catch (ArgumentException ex) // Catches bad Base64 from attachment pre-validation
{
await transaction.RollbackAsync();
_logger.LogError(ex, "Invalid argument during expense creation for project {ProjectId}.", dto.ProjectId);
return ApiResponse<object>.ErrorResponse("Invalid Request Data.", new
{
@ -391,7 +386,6 @@ namespace Marco.Pms.Services.Service
}
catch (Exception ex) // General-purpose catch for unexpected errors (e.g., S3 or DB connection failure)
{
await transaction.RollbackAsync();
_logger.LogError(ex, "An unhandled exception occurred while creating an expense for project {ProjectId}.", dto.ProjectId);
return ApiResponse<object>.ErrorResponse("An internal server error occurred.", new
{

View File

@ -41,6 +41,7 @@
},
"MongoDB": {
"SerilogDatabaseUrl": "mongodb://localhost:27017/DotNetLogs",
"ConnectionString": "mongodb://localhost:27017/MarcoBMS_Caches"
"ConnectionString": "mongodb://localhost:27017/MarcoBMS_Caches",
"ModificationConnectionString": "mongodb://localhost:27017/ModificationLog?authSource=admin&socketTimeoutMS=500&serverSelectionTimeoutMS=500&connectTimeoutMS=500"
}
}