BookingHeChuan/Myshipping.Application/Helper/MapsterExtHelper.cs

67 lines
2.2 KiB
C#

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
{
/// <summary>
/// 动态获取属性对应关系
/// </summary>
/// <typeparam name="TDto"></typeparam>
/// <typeparam name="TEntity"></typeparam>
/// <param name="property">字段代码</param>
/// <returns>返回对应的字段代码</returns>
public static string GetAdaptProperty<TDto, TEntity>(string property)
where TDto : class
where TEntity : class
{
try
{
var adapt = default(TDto).BuildAdapter().CreateMapExpression<TEntity>().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;
}
}
}