using Microsoft.EntityFrameworkCore; using Pf2eModel; using Pf2eModel.Model; using Pf2eModel.Model.Base; using Pf2eModel.Model.Enum; using Pf2eModel.Model.Structure; namespace Pf2eViewer; public class EntityView { public Entity? Entity; public IEntity? SubEntity; public EntityView(Pf2eDbContext context, EntityType type, int id) { Getter? getter = _getters.FirstOrDefault(g => g.Type == type); Entity fullEntity = context .Entities.Where(e => e.Id == id && e.Type == type) .Include(e => e.Sources) .ThenInclude(s => s.Source) .Include(e => e.Keywords) .Include(e => e.Externals) .ThenInclude(x => x.Target) .Include(e => e.Traits) .ThenInclude(t => t.Entity) .FirstOrDefault() ?? throw new Exception("Entity is null"); IEntity? subEntity = (getter != null) ? getter.Get(id, context) : (IEntity?)context.Find(EntityOfTypeAttribute.Resolve(fullEntity), id); Entity = fullEntity; SubEntity = subEntity; } private readonly ICollection _getters = [ new Getter( EntityType.Ancestry, context => context.Ancestries.Include(a => a.AncestryBoosts) ), new Getter( EntityType.Archetype, context => context .Archetypes.Include(a => a.DedicationFeat) .ThenInclude(f => f.Entity) .Include(a => a.Feats) .ThenInclude(f => f.Entity) ), new Getter( EntityType.Background, context => context .Backgrounds.Include(b => b.BackgroundBoosts) .Include(b => b.BackgroundSkills) .ThenInclude(t => t.Training) .Include(b => b.BackgroundItems) ), new Getter( EntityType.Class, context => context .Classes.Include(c => c.ClassKeyAbilities) .Include(c => c.ClassTrainings) .ThenInclude(t => t.Training) .Include(c => c.ClassProgressions) ), new Getter( EntityType.Feat, context => context.Feats.Include(f => f.Archetypes).ThenInclude(a => a.Entity).AsQueryable() ), ]; private abstract class Getter(EntityType type) { public readonly EntityType Type = type; public abstract IEntity? Get(int id, Pf2eDbContext context); } private class Getter(EntityType type, Func> method) : Getter(type) where T : IEntity { public override IEntity? Get(int id, Pf2eDbContext context) { return method.Invoke(context).FirstOrDefault(c => c.Id == id); } } }