LinkedProperty.cs 1.9 KB

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