簡體   English   中英

AutoMapper:如何獲取目標屬性的名稱

[英]AutoMapper: How do I get the name of the destination property

如何獲取目標屬性的名稱:

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));
});

您可以定義這樣的方法:

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;
}

然后像這樣使用它:

var destinationName = GetDestinationPropertyFor<Source, Destination>(mapper, "FirstName");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM