集合映射

AutoMapper 列表、数组、集合映射

只需要配置单个元素 Source → Destination 的映射,集合/数组不用额外写CreateMap,AutoMapper自动处理集合转换

实体

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

public class Destination
{
    public int Value { get; set; }
}Code language: PHP (php)

配置

Mapper.Initialize(cfg =>
{
    // 只配置单个对象映射
    cfg.CreateMap<Source, Destination>();
});Code language: JavaScript (javascript)

支持的集合类型

源和目标都支持

IEnumerableIEnumerable<T>ICollectionICollection<T>IListIList<T>List<T>、数组 T[]

示例

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

// 自动映射为各种集合,不用额外配置
IEnumerable<Destination> ieDest = Mapper.Map<Source[], IEnumerable<Destination>>(sources);
ICollection<Destination> colDest = 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[] arrDest = Mapper.Map<Source[], Destination[]>(sources);Code language: PHP (php)
空集合处理 AllowNullCollections

默认行为:源集合为 null,目标输出空集合,不会赋值为null

修改配置,让源null时目标也为null:

Mapper.Initialize(cfg =>
{
    cfg.AllowNullCollections = true;
    cfg.CreateMap<Source, Destination>();
});Code language: JavaScript (javascript)

集合中的多态

当源集合里面混有父类、子类对象,需要做多态映射,必须使用 .Include<TSourceChild,TDestChild>()

继承实体
//源
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; }
}Code language: JavaScript (javascript)
多态映射配置
Mapper.Initialize(c =>
{
    //父映射 Include 子类映射
    c.CreateMap<ParentSource, ParentDestination>()
        .Include<ChildSource, ChildDestination>();
    //显式声明子类的映射
    c.CreateMap<ChildSource, ChildDestination>();
});Code language: JavaScript (javascript)

使用

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

//数组里面有父、子对象,自动识别实际类型映射
var destinations = Mapper.Map<ParentSource[], ParentDestination[]>(sources);Code language: JavaScript (javascript)

注意:不加Include,子类只会按照父类映射,子类独有的属性会丢失。

项目Profile写法

public class CollectionMappingProfile : Profile
{
    public CollectionMappingProfile()
    {
        CreateMap<Source, Destination>();

        CreateMap<ParentSource, ParentDestination>()
            .Include<ChildSource, ChildDestination>();
        CreateMap<ChildSource, ChildDestination>();
    }
}Code language: HTML, XML (xml)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注