DynamicManyToManyDataGrid.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using InABox.Clients;
  6. using InABox.Core;
  7. namespace InABox.DynamicGrid
  8. {
  9. public class DynamicManyToManyDataGrid<TManyToMany, TThis> : DynamicManyToManyGrid<TManyToMany, TThis>
  10. where TManyToMany : Entity, IPersistent, IRemotable, new() where TThis : Entity, IRemotable, IPersistent, new()
  11. {
  12. private readonly PropertyInfo prop;
  13. public DynamicManyToManyDataGrid()
  14. {
  15. prop = CoreUtils.PropertyList(typeof(TManyToMany), p => p.PropertyType.IsSubclassOf(typeof(EntityLink<TThis>))).FirstOrDefault()
  16. ?? throw new Exception($"No EntityLink property to link entities for DynamicManyToManyGrid<{typeof(TManyToMany)},{typeof(TThis)}>");
  17. }
  18. public Guid ID { get; set; }
  19. protected override Guid[] CurrentGuids()
  20. {
  21. var result = new List<Guid>();
  22. foreach (var row in Data.Rows)
  23. {
  24. var guid = row.Get<Guid>(otherproperty.Name + ".ID");
  25. result.Add(guid);
  26. }
  27. return result.ToArray();
  28. }
  29. protected override TManyToMany CreateItem()
  30. {
  31. var result = base.CreateItem();
  32. var link = prop.GetValue(result) as IEntityLink;
  33. if (link is null)
  34. throw new Exception($"Property {prop.Name} of {typeof(TManyToMany)} is null");
  35. link.ID = ID;
  36. return result;
  37. }
  38. protected override void Reload(Filters<TManyToMany> criteria, Columns<TManyToMany> columns, ref SortOrder<TManyToMany> sort,
  39. Action<CoreTable, Exception> action)
  40. {
  41. var expr = CoreUtils.CreateLambdaExpression<TManyToMany>(prop.Name + ".ID");
  42. criteria.Add(new Filter<TManyToMany>(expr).IsEqualTo(ID));
  43. new Client<TManyToMany>().Query(criteria.Combine(), columns, sort, action);
  44. }
  45. protected override TManyToMany LoadItem(CoreRow row)
  46. {
  47. var id = row.Get<TManyToMany, Guid>(x => x.ID);
  48. return new Client<TManyToMany>()
  49. .Load(
  50. new Filter<TManyToMany>(x => x.ID).IsEqualTo(id))
  51. .FirstOrDefault() ?? throw new Exception($"{typeof(TManyToMany)} with ID {id} does not exist!");
  52. }
  53. protected override void DeleteItems(params CoreRow[] rows)
  54. {
  55. var items = LoadItems(rows);
  56. foreach (var item in items)
  57. new Client<TManyToMany>().Delete(item, "");
  58. }
  59. public override void SaveItem(TManyToMany item)
  60. {
  61. new Client<TManyToMany>().Save(item, "");
  62. }
  63. }
  64. }