簡體   English   中英

Automapper將一個屬性映射到多個

[英]Automapper map one property to multiple

我在源對象和目標對象之間遇到了AutoMapper的挑戰。 我會嘗試解釋這種情況。 在我的src對象上,我有一個字符串,根據它的長度,它應該映射到我的目標對象的多個屬性。

class source
{
   public int Id {get; set;}
   /* some other properties */
   public string Value {get; set;}
}

class destination
{
   public int Id {get; set;}
   /* some other properties with the same name as the source */
   public string Value1 {get; set;}
   public string Value2 {get; set;}
   public string Value3 {get; set;}
}

預期的最大長度為30個字符(可能小於僅映射到兩個屬性或一個屬性的字符)。 因此,每10個將映射到每個目標屬性。 我試圖使用AutoMapper中的ResolveUsing方法,但是沒有辦法讓函數知道我應該帶回哪個段。 所以我想忽略這些屬性的映射,並在Automapper完成其他屬性的工作后手動執行此操作

你可以這樣做是使用.ConstructUsing告訴AutoMapper如何創建對象您可以創建一個手動映射Value1Value2Value3 ,然后讓AutoMapper映射其余屬性的函數。 例如:

static destination ConstructDestination(source src)
{
    List<string> chunked = src.Value
        .Select((ch, index) => new { Character = ch, Index = index })
        .GroupBy(
            grp => grp.Index / 10,
            (key, grp) => new string(grp.Select(itm => itm.Character).ToArray()))
        .ToList();

    var dest = new destination
    {
        Value1 = chunked.Count > 0 ? chunked[0] : null,
        Value2 = chunked.Count > 1 ? chunked[1] : null,
        Value3 = chunked.Count > 2 ? chunked[2] : null
    };

    return dest;
}

Mapper.CreateMap<source, destination>()
    .ConstructUsing(ConstructDestination)
    .ForMember(dest => dest.Value1, opt => opt.Ignore())
    .ForMember(dest => dest.Value2, opt => opt.Ignore())
    .ForMember(dest => dest.Value3, opt => opt.Ignore());
    /* Id is mapped automatically. */

當然,如果在實際場景中你有三個以上的Value字段,這可能會變得很討厭 - 在這種情況下你可以使用反射來設置屬性。

您可以使用ForMember規范創建映射函數

private void CreateMap(){
    Mapper.CreateMap<source,destination>()
        .ForMember(v=> v.Value1,
            opts => opts.MapFrom( src=> src.Value.Substring(0,10)))
        .ForMember(v=> v.Value2,
            opts => opts.MapFrom( src=> src.Value.Substring(10,10)))
        .ForMember(v=> v.Value3,
            opts => opts.MapFrom( src=> src.Value.Substring(20,10)));
}

您可以只評估原始字符串包含適當長度的每個映射,否則返回string.Empty或填充它以滿足您的需要。

用法(使用LinqPad):

void Main(){
   CreateMap();
   var source = new source();
   source.Id=1;
   source.Value="123454678901234546789012345467";
   var res = Mapper.Map<destination>(source);
   res.Dump();
}

暫無
暫無

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

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