簡體   English   中英

使用自動映射器按慣例展開

[英]Unflatten by convention with automapper

在我的項目中,我嘗試使用 automapper 盡可能按照約定將我的命令對象展開為我的域對象。
當我明確 map 映射配置文件中的兩個成員時,它可以工作,但根據 automapper 文檔,我認為這也應該按慣例工作。 我創建了一個 dotnetfiddle來演示最小的情況。

相關問題最終會導致人們明確添加映射,但這與 Automapper 的構建目的和文檔相矛盾,不是嗎? 它也不適用於展平,所以我認為反向圖是一個紅鯡魚。

映射

public class Mapping: Profile
{
    public Mapping()
    {
        this.CreateMap<CreateSelectionCommand, Selection>();
        // .ForMember(selection => selection.Name, opt => opt.MapFrom(x => x.SelectionName))
        .reverseMap()
    }
}

我期望的工作

[Fact]
public void ShouldMapName()
{
    var cmd = new CreateSelectionCommand {SelectionName = "selectionName"};
    var selection = _mapper.Map<Selection>(cmd);

    Assert.Equal(cmd.SelectionName, selection.Name); <== selection.Name == ""
}

上下文類

public class Selection
{
    public string Name { get; set; }
}

public class CreateSelectionCommand
{
    public string SelectionName { get; set; }
}

我是誤讀了文檔還是遺漏了什么?

展平是關於將嵌套的“復雜”對象映射到“更高”級別的屬性,即在您的情況下,如果CreateSelectionCommand具有具有Name屬性的類型的屬性Selection ,它將被映射到目標類型中的SelectionName (參見this fiddle )。

您可以嘗試通過添加以下內容來使用前綴

cfg.RecognizePrefixes("Selection");

到您的配置(請參閱this fiddle ),但我懷疑它是否適合基於約定的處理。

此外,您似乎可以使用ISourceToDestinationNameMapperAddMemberConfiguration添加自定義名稱約定:

class TypeNamePrefixedSourceToDestinationNameMapper : ISourceToDestinationNameMapper
{
    public MemberInfo GetMatchingMemberInfo(IGetTypeInfoMembers getTypeInfoMembers, TypeDetails typeInfo,
        Type destType,
        Type destMemberType, string nameToSearch)
    {
        return getTypeInfoMembers.GetMemberInfos(typeInfo)
            .FirstOrDefault(mi => mi.Name == destType.Name + nameToSearch);
    }
}

var config = new MapperConfiguration(cfg =>
{
    cfg.AddMemberConfiguration().AddName<TypeNamePrefixedSourceToDestinationNameMapper>();

    // ...
}

至少它適用於這種簡單的情況,請參閱this fiddle

暫無
暫無

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

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