业务描述
Mapster,LambdaExpression 通过一个类(ENTITY)中的一个属性名动态获取另一人类(MODEL)的对应属性名
如下图两个类,在泛型中通过参数类Entity中的属性名动态获取MODEL中对应的属性名。比如参数为 “fName” 得到的是 “F_NAME”
类图业务场景
》泛型(public class Base<TDto,TEntity>where TEntity : class, new() where TDto : class, new(){})
》Mapster(C#插件) 、LambdaExpression
业务方法
/// <summary>
/// 动态获取属性对应关系
/// </summary>
/// <param name="dto">源</param>
/// <param name="property">要查找的属性</param>
/// <returns></returns>
private string GetAdaptProperty(TDto dto, string property)
{
try
{
var adapt = dto.BuildAdapter().CreateMapExpression<TEntity>().Body as BlockExpression;
foreach (var item in adapt.Expressions) {
if (item.NodeType.ToString() == "Try")
{
var tryExpression = item as TryExpression;
var block = tryExpression.Body as BlockExpression;
if (block != null) { foreach (var itm in block.Expressions)
{ if (itm.NodeType.ToString() == "Block")
{
var binaries = (itm as BlockExpression).Expressions;
foreach (var binary in binaries)
{
var member = (binary as BinaryExpression).Right as MemberExpression;
if (member.Member.Name.Equals(property))
{
member = (binary as BinaryExpression).Left as MemberExpression;
return member.Member.Name;
}
}
}
}
}
}
}
return property;
} catch (Exception ex)
{
ex.Message.LogError<TDto>();
return property;
}
}
}
网友评论