EquipmentStore.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using Comal.Classes;
  4. using InABox.Core;
  5. using System;
  6. namespace Comal.Stores
  7. {
  8. public class EquipmentStore : SchedulableStore<Equipment>
  9. {
  10. protected override void AfterSave(Equipment entity)
  11. {
  12. UpdateLinkedTracker(entity);
  13. base.AfterSave(entity);
  14. }
  15. private void UpdateLinkedTracker(Equipment entity)
  16. {
  17. if (entity.TrackerLink.HasOriginalValue(x => x.ID))
  18. {
  19. var oldID = entity.TrackerLink.GetOriginalValue(x => x.ID);
  20. var newID = entity.TrackerLink.ID;
  21. // If there are any other equipment items with the same tracker
  22. // blank them out - a tracker can only be attached to one equipment item
  23. var equips = Provider.Query(
  24. new Filter<Equipment>(x => x.TrackerLink.ID).IsEqualTo(newID).And(x => x.ID)
  25. .IsNotEqualTo(entity.ID),
  26. Columns.None<Equipment>().Add(x => x.ID).Add(x => x.TrackerLink.ID)
  27. ).ToList<Equipment>();
  28. if (equips.Any())
  29. {
  30. foreach (var equip in equips)
  31. equip.TrackerLink.ID = Guid.Empty;
  32. Provider.Save(equips);
  33. }
  34. var trackers = Provider.Query(
  35. new Filter<GPSTracker>(x => x.ID).IsEqualTo(oldID).Or(x => x.ID).IsEqualTo(newID).Or(x=>x.Equipment.ID).IsEqualTo(entity.ID),
  36. Columns.None<GPSTracker>().Add(x => x.ID, x => x.Equipment.ID)
  37. ).ToList<GPSTracker>();
  38. // If there are any other trackers attached to this equipment item,
  39. // clear them out - an equipment item can only have one tracker
  40. foreach (var tracker in trackers)
  41. tracker.Equipment.ID = Guid.Empty;
  42. // Update the equipment item with the new Tracker ID
  43. var curr = trackers.FirstOrDefault(x => x.ID.Equals(newID));
  44. if (curr != null)
  45. curr.Equipment.ID = entity.ID;
  46. // Save any changes
  47. if (trackers.Any(x=>x.IsChanged()))
  48. Provider.Save(trackers);
  49. }
  50. }
  51. }
  52. }