C# 自动映射:如何获取目标属性的名称
如何获取目标属性的名称:C# 自动映射:如何获取目标属性的名称,c#,automapper,automapper-4,C#,Automapper,Automapper 4,如何获取目标属性的名称: Public class Source{ public string FirstName{ get; set; } } public class Destination{ public string C_First_Name{ get; set; } } 使用AutoMapper,在传递源属性名称时,如何获取目标属性的名称 对于某些地图配置: var mapper = new MapperConfiguration(cfg => { c
Public class Source{
public string FirstName{ get; set; }
}
public class Destination{
public string C_First_Name{ get; set; }
}
使用AutoMapper,在传递源属性名称时,如何获取目标属性的名称 对于某些地图配置:
var mapper = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>().ForMember(dst => dst.C_First_Name, opt => opt.MapFrom(src => src.FirstName));
});
var-mapper=new-MapperConfiguration(cfg=>
{
cfg.CreateMap().formMember(dst=>dst.C_First_Name,opt=>opt.MapFrom(src=>src.FirstName));
});
您可以定义如下所示的方法:
public string GetDestinationPropertyFor<TSrc, TDst>(MapperConfiguration mapper, string sourceProperty)
{
var map = mapper.FindTypeMapFor<TSrc, TDst>();
var propertyMap = map.GetPropertyMaps().First(pm => pm.SourceMember == typeof(TSrc).GetProperty(sourceProperty));
return propertyMap.DestinationProperty.Name;
}
公共字符串GetDestinationPropertyFor(MapperConfiguration映射器,字符串sourceProperty)
{
var map=mapper.FindTypeMapFor();
var propertyMap=map.getpropertymap().First(pm=>pm.SourceMember==typeof(TSrc.GetProperty(sourceProperty));
返回propertyMap.DestinationProperty.Name;
}
然后像这样使用它:
var destinationName = GetDestinationPropertyFor<Source, Destination>(mapper, "FirstName");
var destinationName=GetDestinationPropertyFor(映射器,“FirstName”);
当我传递源属性名称时,如何获取目标属性的名称。不清楚您在问什么。请问您为什么需要该属性名称?如果有多个目的地属性呢?(您可以多次映射源)。不,我不需要映射。当我通过FirstName时,我应该能够得到C_First_Name。它是目的地的名称。对不起,我不明白你在问什么。你能添加一个例子吗?请看一看:我的要求非常简单:我将传递源属性的名称(FirstName),我想获得目标属性的名称(C_FIrst_name)。如果你有任何问题,请告诉我。这篇文章有点过时了,但问题仍然有效。下面是另一篇更为时新的文章,讨论了同样的问题: