using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using InABox.Clients; using InABox.Core; namespace InABox.DynamicGrid { public class DynamicManyToManyDataGrid : DynamicManyToManyGrid where TManyToMany : Entity, IPersistent, IRemotable, new() where TThis : Entity, IRemotable, IPersistent, new() { private readonly PropertyInfo prop; public DynamicManyToManyDataGrid() { prop = CoreUtils.PropertyList(typeof(TManyToMany), p => p.PropertyType.IsSubclassOf(typeof(EntityLink))).FirstOrDefault() ?? throw new Exception($"No EntityLink property to link entities for DynamicManyToManyGrid<{typeof(TManyToMany)},{typeof(TThis)}>"); } public Guid ID { get; set; } protected override Guid[] CurrentGuids() { var result = new List(); foreach (var row in Data.Rows) { var guid = row.Get(otherproperty.Name + ".ID"); result.Add(guid); } return result.ToArray(); } protected override TManyToMany CreateItem() { var result = base.CreateItem(); var link = prop.GetValue(result) as IEntityLink; if (link is null) throw new Exception($"Property {prop.Name} of {typeof(TManyToMany)} is null"); link.ID = ID; return result; } protected override void Reload(Filters criteria, Columns columns, ref SortOrder sort, Action action) { var expr = CoreUtils.CreateLambdaExpression(prop.Name + ".ID"); criteria.Add(new Filter(expr).IsEqualTo(ID)); new Client().Query(criteria.Combine(), columns, sort, action); } protected override TManyToMany LoadItem(CoreRow row) { var id = row.Get(x => x.ID); return new Client() .Load( new Filter(x => x.ID).IsEqualTo(id)) .FirstOrDefault() ?? throw new Exception($"{typeof(TManyToMany)} with ID {id} does not exist!"); } protected override void DeleteItems(params CoreRow[] rows) { var items = LoadItems(rows); foreach (var item in items) new Client().Delete(item, ""); } public override void SaveItem(TManyToMany item) { new Client().Save(item, ""); } } }