diff --git a/DiunaBI.API/Controllers/LayersController.cs b/DiunaBI.API/Controllers/LayersController.cs index f35fdde..353b71f 100644 --- a/DiunaBI.API/Controllers/LayersController.cs +++ b/DiunaBI.API/Controllers/LayersController.cs @@ -994,20 +994,35 @@ public class LayersController : Controller try { // Get the most recent "Deleted" history entry for each unique RecordId in this layer - var deletedRecords = _db.RecordHistory - .Include(h => h.ChangedBy) + // First, get all deleted record history entries + var deletedHistoryEntries = _db.RecordHistory .Where(h => h.LayerId == layerId && h.ChangeType == RecordChangeType.Deleted) + .ToList(); + + // Group in memory and get the most recent deletion for each record + var mostRecentDeletes = deletedHistoryEntries .GroupBy(h => h.RecordId) - .Select(g => g.OrderByDescending(h => h.ChangedAt).FirstOrDefault()) - .Where(h => h != null) + .Select(g => g.OrderByDescending(h => h.ChangedAt).First()) + .ToList(); + + // Get all unique user IDs from the history entries + var userIds = mostRecentDeletes.Select(h => h.ChangedById).Distinct().ToList(); + + // Load the users + var users = _db.Users + .Where(u => userIds.Contains(u.Id)) + .ToDictionary(u => u.Id, u => u.UserName ?? string.Empty); + + // Build the DTOs + var deletedRecords = mostRecentDeletes .Select(h => new DeletedRecordDto { - RecordId = h!.RecordId, + RecordId = h.RecordId, Code = h.Code, Desc1 = h.Desc1, DeletedAt = h.ChangedAt, DeletedById = h.ChangedById, - DeletedByName = h.ChangedBy != null ? h.ChangedBy.UserName ?? string.Empty : string.Empty + DeletedByName = users.TryGetValue(h.ChangedById, out var userName) ? userName : string.Empty }) .OrderByDescending(d => d.DeletedAt) .ToList();