嵌套实体是一个常见的数据结构。Automapper是一个流行的映射库,可以用来方便地将一个类的属性映射到另一个类中。这个库特别适合用于将数据库中的实体映射到ViewModel或DTO中。
在Automapper中,嵌套实体映射存在一些最佳实践,包括以下几点:
不要使用.forMember()方法配置嵌套的实体类型。
使用AutoMapper Profile来配置映射规则。
除非需要自定义映射方式,否则应该优先使用默认规则来映射实体类型。
下面是一个包含代码示例的解决方案:
// 数据库实体类 public class Book { public int Id { get; set; } public string Title { get; set; } public Author Author { get; set; } }
public class Author { public int Id { get; set; } public string Name { get; set; } }
// DTO类 public class BookDto { public int Id { get; set; } public string Title { get; set; } public AuthorDto Author { get; set; } }
public class AuthorDto { public string Name { get; set; } }
// AutoMapper Profile类
public class BookProfile : Profile
{
public BookProfile()
{
CreateMap
// 使用 AutoMapper 映射实体
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile
var mapper = config.CreateMapper();
var book = new Book { Id = 1, Title = "C#入门到精通", Author = new Author { Id = 1, Name = "张三" } };
var bookDto = mapper.Map
// 输出结果: // { // "id": 1, // "title": "C#入门到精通", // "author": { // "name": "张三" // } // }