// Program.cs
var mapper = InitializeMapper();
var dao = new Walterlv1Dao
Id = "2ed3558ac938438fb2c1d2de71d7bb90",
Name = "walterlv",
Text = "blog.walterlv.com",
;
var vo = mapper.Map<Walterlv1Vo>(dao);
Console.WriteLine($"Name = vo.Name, Text = vo.Text");
static IMapper InitializeMapper()
var configuration = new MapperConfiguration(cfg =>
cfg.CreateMap<Walterlv1Dao, Walterlv1Vo>();
);
#if DEBUG
configuration.AssertConfigurationIsValid();
#endif
var mapper = configuration.CreateMapper();
return mapper;
在这段代码中:
我们定义了一个方法 InitializeMapper,在里面初始化 IMapper 的新实例。
初始化 MapperConfiguration,定义类型的映射关系
在 DEBUG 下验证 MapperConfiguration 的映射是否正确
创建一个 IMapper 的映射器,用于后续映射使用
我们初始化了一个 Walterlv1Dao 类的实例
我们调用 mapper.Map 将其映射到 Walterlv1Vo 类型
这两个类型的定义如下(虽然无关紧要)。
1
2
3
4
5
6
7
8
9
10
11
12
public class Walterlv1Dao
public string? Id get; set;
public string? Name get; set;
public string? Text get; set;
public class Walterlv1Vo
public string? Id get; set;
public string? Name get; set;
public string? Text get; set;
如果你的应用程序中会使用到依赖注入,那么只需要把拿到的 IMapper 加入即可。
如果希望两个类型之间能够双向映射,那么在初始化 IMapper 的时候也应该再额外调用一下 ReverseMap 方法,否则就会抛出异常 AutoMapper.AutoMapperMappingException:“Missing type map configuration or unsupported mapping.”。
public class Walterlv1Dao
public string? Id get; set;
public string? Name get; set;
public FriendDao? Friend get; set;
public class FriendDao
public string? Id get; set;
public string? Name get; set;
public class Walterlv1Vo
public string? Id get; set;
public string? Name get; set;
public FriendVo? Friend get; set;
public class FriendVo
public string? Id get; set;
public string? Name get; set;
public class Walterlv1Dao
public string? Id get; set;
public string? Name get; set;
public List<FriendDao>? Friend get; set;
public class Walterlv1Vo
public string? Id get; set;
public string? Name get; set;
public List<FriendVo>? Friend get; set;
参考资料
AutoMapper/AutoMapper: A convention-based object-object mapper in .NET.