LinkedProperty.cs 2.7 KB

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