using Furion.FriendlyException; using Mapster; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Myshipping.Application.Helper { public static class MapsterExtHelper { /// /// 动态获取属性对应关系 /// /// /// /// 字段代码 /// 返回对应的字段代码 public static string GetAdaptProperty(string property) where TDto : class where TEntity : class { try { var adapt = default(TDto).BuildAdapter().CreateMapExpression().Body as BlockExpression; var tryInfo = adapt.Expressions.FirstOrDefault(a => a.NodeType.ToString() == "Try"); if (tryInfo == null) throw Oops.Oh($"{nameof(GetAdaptProperty)} 读取TRY异常"); var block = ((TryExpression)tryInfo).Body as BlockExpression; if (block == null) throw Oops.Oh($"{nameof(GetAdaptProperty)} 读取BlockExpression异常"); var blockNode = block.Expressions.FirstOrDefault(t => t.NodeType.ToString() == "Block"); var member = (blockNode as BlockExpression).Expressions.Where(t => { var right = ((t as BinaryExpression).Right as MemberExpression); if (right == null) return false; var currInfo = right.Member; return currInfo.Name.Equals(property, StringComparison.OrdinalIgnoreCase); }).FirstOrDefault(); if (member != null) return ((member as BinaryExpression).Left as MemberExpression).Member.Name; } catch (Exception ex) { throw Oops.Oh($"{nameof(GetAdaptProperty)} 读取BlockExpression异常"); } return string.Empty; } } }