shoc-backend/SeaHaven.DataServices/Implementation/WorkOrderAuditDataService.cs

44 lines
1.4 KiB
C#
Raw Normal View History

using Data.SeaHavenIndustries;
using Microsoft.EntityFrameworkCore;
using SeaHaven.DataServices.Interfaces;
namespace SeaHaven.DataServices.Implementation
{
public class WorkOrderAuditDataService : IWorkOrderAuditDataService
{
private readonly ApplicationDbContext _context;
public WorkOrderAuditDataService(ApplicationDbContext context)
{
_context = context;
}
public void EnqueueAuditLog(WorkOrderAuditLog auditLog)
{
_context.WorkOrderAuditLogs.Add(auditLog);
}
public async Task PersistAsync(CancellationToken cancellationToken)
{
try
{
await _context.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException ex) when (IsUniqueConstraintViolation(ex))
{
foreach (var entry in ex.Entries.Where(e => e.Entity is WorkOrderFieldLock))
entry.State = EntityState.Detached;
await _context.SaveChangesAsync(cancellationToken);
}
}
private static bool IsUniqueConstraintViolation(DbUpdateException ex)
{
var message = ex.InnerException?.Message ?? ex.Message;
return message.Contains("duplicate", StringComparison.OrdinalIgnoreCase)
|| message.Contains("UNIQUE", StringComparison.OrdinalIgnoreCase);
}
}
}