123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- using System;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- using FluentResults;
- namespace InABox.Core
- {
- public interface ILinkedProperty
- {
- Type Type { get; }
- String Path { get; }
- String Source { get; }
- String Target { get; }
- void Update(object? from, object? to);
- /// <summary>
- /// This equality comparer checks against type, path, source and target
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- bool Equals(object obj);
- }
- public class LinkedProperty<TLinkedEntity, TEntityLink, TType> : ILinkedProperty
- where TLinkedEntity : class
- where TEntityLink : class
- {
- public Type Type => typeof(TLinkedEntity);
- public String Path { get; }
- private Func<TEntityLink?, TType> _source;
- public String Source { get; }
- public String Target { get; }
- private readonly Func<TLinkedEntity?, TType, Result<TType>>? _func;
-
- public override string ToString()
- {
- return $"{Type.EntityName().Split('.').Last()}: {Path}{(String.IsNullOrWhiteSpace(Path) ? "" : ".")}{Source} => {Target}";
- }
-
- public LinkedProperty(Expression<Func<TLinkedEntity, TEntityLink>> path,
- Expression<Func<TEntityLink?, TType>> source,
- Expression<Func<TLinkedEntity?, TType>> target,
- Func<TLinkedEntity?,TType, Result<TType>>? func = null)
- {
- Path = CoreUtils.GetFullPropertyName(path, ".");
- Source = CoreUtils.GetFullPropertyName(source, ".");
- Target = CoreUtils.GetFullPropertyName(target,".");
- _func = func;
- _source = source.Compile();
- }
- public void Update(object? from, object? to)
- {
- if (from != null && to != null)
- {
- var value = _source.Invoke(from as TEntityLink);
- //var value = CoreUtils.GetPropertyValue(from, Source);
- if (_func != null)
- {
- var result = _func(to as TLinkedEntity, value);
- if (!result.IsSuccess)
- return;
- value = result.Value;
- }
- CoreUtils.SetPropertyValue(to, Target, value);
- }
- }
- public override bool Equals(object obj)
- {
- if (obj is ILinkedProperty src)
- {
- return
- (obj as ILinkedProperty).Type == Type &&
- String.Equals(src.Path,Path)
- && String.Equals(src.Source, Source)
- && String.Equals(src.Target, Target);
- }
- return false;
- }
- }
- }
|