【问题标题】:Mapping a List using a Custom Resolver with Automapper使用带有 Automapper 的自定义解析器映射列表
【发布时间】:2014-08-05 21:16:13
【问题描述】:

我有 2 个对象需要相互映射。它们看起来像

public class Example1
{
     CustomType1 Prop { get; set; }
     List<CustomType1> List { get; set; } 
}

public class Example2
{
    Customtype2 Prop { get; set; }
    List<Customtype2> List { get; set; } 
}

public class CustomType1
{
    public string SomeString { get; set; }
}

public class Customtype2
{
    public string FirstPartOfSomeString { get; set; }

    public string SecondPartOfSomeString { get; set; }
}

我想制作一个将 CustomType1 映射到 CustomType2 的 CustomResolver,然后在列表中使用该解析器。例如,

Mapper.CreateMap<Example1, Example2>()
            .ForMember(d => d.Prop, opt => opt.ResolveUsing(myCustomResolver))
            .ForMember(d => d.List, opt => opt.ResolveUsing( /*use myCustomResolver on a list here*/));

我尝试过使用类似的东西:

Mapper.CreateMap<Example1, Example2>()
            .ForMember(d => d.Prop, opt => opt.ResolveUsing(myCustomResolver))
            .ForMember(d => d.List, opt => opt.MapFrom(s => s.List.Select(myCustomResolver.Resolve).ToList()));

但我似乎遗漏了什么。有没有办法用 AutoMapper 做到这一点?

【问题讨论】:

  • 请发布 CustomResolver 代码。

标签: c# collections mapping automapper


【解决方案1】:

您是否尝试过在自定义类型之间添加映射而不是使用解析器? AutoMapper 足够智能,可以重复使用列表的映射...

Mapper.CreateMap<CustomType1, CustomType2>()
    .ForMember(x => FirstPartOfSomeString, opts => opts.MapFrom(x => x.SomeString.Substring(5)))
    .ForMember(x => SecondPartOfSomeString, opts => opts.MapFrom(x => x.SomeString.Substring(5, 5)));

Mapper.CreateMap<Example1, Example2>();

【讨论】:

  • 这行得通。如果您在映射集合之前定义了 CustomType1 到 CustomType2 映射,那么您可以将映射与列表重用。谢谢。
猜你喜欢
  • 2015-10-20
  • 2023-04-03
  • 2020-10-15
  • 2017-02-17
  • 1970-01-01
  • 2014-03-27
  • 2013-05-09
  • 2011-08-01
  • 2020-05-20
相关资源
最近更新 更多