AutoMapper官方文档(九)【列表和数组】

AutoMapper只需要配置元素类型,而不是任何可能使用的数组或列表类型。 例如,我们可能有一个简单的源和目标类型:

public class Source
{
    public int Value { get; set; }
}

public class Destination
{
    public int Value { get; set; }
}

所有基本的泛型集合类型都被支持:

Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>());

var sources = new[]
    {
        new Source { Value = 5 },
        new Source { Value = 6 },
        new Source { Value = 7 }
    };

IEnumerable<Destination> ienumerableDest = Mapper.Map<Source[], IEnumerable<Destination>>(sources);
ICollection<Destination> icollectionDest = Mapper.Map<Source[], ICollection<Destination>>(sources);
IList<Destination> ilistDest = Mapper.Map<Source[], IList<Destination>>(sources);
List<Destination> listDest = Mapper.Map<Source[], List<Destination>>(sources);
Destination[] arrayDest = Mapper.Map<Source[], Destination[]>(sources);

具体而言,支持的源集合类型包括:

    IEnumerable
    IEnumerable<T>
    ICollection
    ICollection<T>
    IList
    IList<T>
    List<T>
    Arrays

对于非泛型可枚举类型,仅支持未映射的可指定类型,因为AutoMapper将无法“猜测”您尝试映射的类型。 如上例所示,没有必要显式配置列表类型,只有它们的成员类型。

映射到现有集合时,首先清除目标集合。 如果这不是你想要的,看看AutoMapper.Collection

集合中的多态元素类型

很多时候,我们的源和目标类型都可能有一个类型的层次结构。 AutoMapper支持多态数组和集合,如果找到,则使用派生的源/目标类型。

public class ParentSource
{
    public int Value1 { get; set; }
}

public class ChildSource : ParentSource
{
    public int Value2 { get; set; }
}

public class ParentDestination
{
    public int Value1 { get; set; }
}

public class ChildDestination : ParentDestination
{
    public int Value2 { get; set; }
}

AutoMapper仍然需要显式配置子映射,因为AutoMapper不能“猜测”要使用的特定子目标映射。 以下是上述类型的示例:

Mapper.Initialize(c=> {
    c.CreateMap<ParentSource, ParentDestination>()
         .Include<ChildSource, ChildDestination>();
    c.CreateMap<ChildSource, ChildDestination>();
});

var sources = new[]
    {
        new ParentSource(),
        new ChildSource(),
        new ParentSource()
    };

var destinations = Mapper.Map<ParentSource[], ParentDestination[]>(sources);

destinations[0].ShouldBeInstanceOf<ParentDestination>();
destinations[1].ShouldBeInstanceOf<ChildDestination>();
destinations[2].ShouldBeInstanceOf<ParentDestination>();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值