用法
public async Task<List<PayInfoDto>> TestMapMulti2One()
{
var result = from variety in _varietyRepository.GetAll()
join product in _productRepository.GetAll() on variety.Id equals product.BasBloodVarietyId
select Dynamic.MapMulti2One<PayInfoDto>(variety, product);
return result.ToList();
}
实体类
public class PayInfoDto
{
public string Name { get; set; }
//这个字段 取 BasBloodProduct表的 Name字段
[MapAttribute("BasBloodProduct", "Name")]
public string ProductName { get; set; }
}
特性方法
public class OtherMapMult
{
public string TableName { get; set; }
public string SetName { get; set; }
public string GetName { get; set; }
}
public class MapAttribute : Attribute
{
private string _tableName { get; set; }
private string _setName { get; set; }
public MapAttribute(string tableName,string setName)
{
_tableName = tableName;
_setName = setName;
}
public OtherMapMult MapValidate()
{
return new OtherMapMult {
SetName=_setName,
TableName=_tableName,
};
}
}
方便映射的公共方法
//把入参的属性赋值给出参
public static T MapMulti2One<T>(params object[] arrObj) where T : new()
{
//检查是否存在特性
// 使用反射获取A和B对象的属性信息 要映射的对象 Dto
var propertiesT = typeof(T).GetProperties();
List<OtherMapMult> list = new List<OtherMapMult>();
foreach (var prop in propertiesT)
{
//查看属性是否具有 MapAttribute特性
if (prop.IsDefined(typeof(MapAttribute), true))
{
foreach (MapAttribute itemMapAttribute in prop.GetCustomAttributes(typeof(MapAttribute), true))//获取字段所有的特性
{
var itemMap = itemMapAttribute.MapValidate();
if (itemMap!=null)
{
itemMap.GetName=prop.Name;
list.Add(itemMap);
}
}
}
}
//遍历数据映射
var t = new T();
foreach (var item in arrObj)
{
if (item==null) {
continue;
}
var propertiesA = item.GetType().GetProperties();
foreach (var propertyA in propertiesA)
{
var teGetVuale = list.FirstOrDefault(ta => ta.SetName == propertyA.Name && ta.TableName == propertyA.DeclaringType.Name);
var propertyT = propertiesT
.FirstOrDefault(p => p.Name == (teGetVuale?.GetName ?? propertyA.Name) && p.PropertyType == propertyA.PropertyType);
if (propertyT != null)
{
var value = propertyA.GetValue(item);
var convertedValue = Convert.ChangeType(value, propertyT.PropertyType);
propertyT.SetValue(t, convertedValue);
}
}
}
return t;
}