LinkedProperty.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4. using System.Reflection;
  5. namespace InABox.Core
  6. {
  7. public interface ILinkedProperty
  8. {
  9. Type Type { get; }
  10. String Path { get; }
  11. String Source { get; }
  12. String Target { get; }
  13. void Update(object? from, object? to);
  14. /// <summary>
  15. /// This equality comparer checks against type, path, source and target
  16. /// </summary>
  17. /// <param name="obj"></param>
  18. /// <returns></returns>
  19. bool Equals(object obj);
  20. }
  21. public class LinkedProperty<TLinkedEntity, TEntityLink, TType> : ILinkedProperty
  22. {
  23. public Type Type => typeof(TLinkedEntity);
  24. public String Path { get; }
  25. public String Source { get; }
  26. public String Target { get; }
  27. public override string ToString()
  28. {
  29. return $"{Type.EntityName().Split('.').Last()}: {Path}{(String.IsNullOrWhiteSpace(Path) ? "" : ".")}{Source} => {Target}";
  30. }
  31. public LinkedProperty(Expression<Func<TLinkedEntity, TEntityLink>> path,
  32. Expression<Func<TEntityLink, TType>> source,
  33. Expression<Func<TLinkedEntity, TType>> target)
  34. {
  35. Path = CoreUtils.GetFullPropertyName(path, ".");
  36. Source = CoreUtils.GetFullPropertyName(source, ".");
  37. Target = CoreUtils.GetFullPropertyName(target,".");
  38. }
  39. public void Update(object? from, object? to)
  40. {
  41. if (from != null && to != null)
  42. {
  43. var value = CoreUtils.GetPropertyValue(from, Source);
  44. CoreUtils.SetPropertyValue(to, Target, value);
  45. }
  46. }
  47. public override bool Equals(object obj)
  48. {
  49. if (obj is ILinkedProperty src)
  50. {
  51. return
  52. (obj as ILinkedProperty).Type == Type &&
  53. String.Equals(src.Path,Path)
  54. && String.Equals(src.Source, Source)
  55. && String.Equals(src.Target, Target);
  56. }
  57. return false;
  58. }
  59. }
  60. }