以下是使用Automapper将DTO和数组转换为列表的代码示例:
using AutoMapper;
using System;
using System.Collections.Generic;
public class SourceDTO
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Destination
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
// 初始化Automapper映射配置
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap();
});
var mapper = config.CreateMapper();
// 示例1:将单个DTO对象转换为目标对象
var sourceDTO = new SourceDTO { Id = 1, Name = "DTO1" };
var destination = mapper.Map(sourceDTO);
Console.WriteLine($"Id: {destination.Id}, Name: {destination.Name}");
// 示例2:将DTO数组转换为目标对象列表
var sourceDTOArray = new SourceDTO[]
{
new SourceDTO { Id = 1, Name = "DTO1" },
new SourceDTO { Id = 2, Name = "DTO2" },
new SourceDTO { Id = 3, Name = "DTO3" }
};
var destinationList = mapper.Map, List>(sourceDTOArray);
foreach(var item in destinationList)
{
Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
}
}
}
在上面的代码示例中,我们首先创建了两个类SourceDTO
和Destination
,它们表示源DTO和目标对象的属性。
然后,我们初始化了Automapper的映射配置。在这个例子中,我们只有一个映射从SourceDTO
到Destination
,这是通过调用CreateMap
来实现的。
接下来,我们使用配置创建了一个Mapper
对象。然后,我们可以使用Map
方法将单个DTO对象或DTO数组转换为目标对象或目标对象列表。
在示例1中,我们将单个DTO对象转换为目标对象,并打印转换后的属性值。
在示例2中,我们将DTO数组转换为目标对象列表,并使用foreach
循环打印每个目标对象的属性值。
请注意,你需要在项目中安装Automapper NuGet包才能成功运行上述代码。