using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data.Manuals; using AsbCloudApp.Repositories; using AsbCloudDb.Model; using AsbCloudDb.Model.Manuals; using Mapster; using Microsoft.EntityFrameworkCore; namespace AsbCloudInfrastructure.Repository; public class ManualFolderRepository : CrudRepositoryBase, IManualFolderRepository { public ManualFolderRepository(IAsbCloudDbContext context) : base(context) { } public async Task> GetTreeAsync(int idCategory, CancellationToken cancellationToken) { var folders = await dbContext.ManualFolders .Where(m => m.IdCategory == idCategory) .AsNoTracking() .Include(m => m.Manuals) .Include(m => m.Parent) .ToArrayAsync(cancellationToken); return BuildTree(folders).Select(x => x.Adapt()); } public async Task GetOrDefaultAsync(string name, int? idParent, int idCategory, CancellationToken cancellationToken) { var entity = await dbContext.ManualFolders .FirstOrDefaultAsync(m => m.Name == name && m.IdCategory == idCategory && m.IdParent == idParent, cancellationToken); if (entity is null) return null; return Convert(entity); } private IEnumerable BuildTree(IEnumerable folders) { var folderDict = folders.ToDictionary(f => f.Id); foreach (var folder in folders) { if (folder.IdParent.HasValue && folderDict.TryGetValue(folder.IdParent.Value, out var parent)) { parent.Children ??= new List(); parent.Children.Add(folder); } } return folders.Where(f => f.IdParent == null); } }