c# - Automapper 将一个属性映射到多个

标签 c# visual-studio-2010 automapper automapper-2 automapper-3

我在源对象和目标对象之间面临 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 如何创建对象 您可以创建一个映射 Value1Value2< 的函数, Value3 手动,然后让 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 字段,这可能会变得很糟糕——在这种情况下您可以使用反射来设置属性。

关于c# - Automapper 将一个属性映射到多个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917270/

相关文章:

Automapper 8-表达式树lambda不得包含空传播运算符

c# - 升级到 9 后无法访问自动映射器上下文项

c# - 如何使用 AutoMapper 将多个子类映射到一个类中?

c# - 在Azure包MSBuild过程中执行.py

c# - 如何在不借助 P/Invoke 或反射的情况下在 .NET 中启用 SeCreateGlobalPrivilege?

C# MySql 查询结果到组合框

c# - System.Speech 降低麦克风灵敏度

vb.net - 分割字符串数组时出现问题

c++ - 分析故障转储文件

c# - Datagridview控件单元中的数据验证