繁体   English   中英

AutoMapper unflattening with naming convention 导致 null object

[英]AutoMapper unflattening with naming convention results in null object

我正在使用 AutoMapper 11.0.0 到 map 一个 DTO 到另一个 class。

我的目标是 map SupplierDto.CreatedByIdSupplierDto.CreatedByNameSupplier.CreatedBy.IdSupplier.CreatedBy.Name

阅读文档,我发现 AutoMapper 有一个 unflattening 特性,它使用 PascalCase 命名约定到 map 源到目标对象,而不需要逐个映射成员。

问题是我遗漏了一些东西,因为我的类是按照约定命名的,而且我得到了 null 个对象。

这是我的课程:

供应商.cs

public class Supplier
{
    public long Id { get; set; }
    public string Name { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
    public User CreatedBy { get; set; }
    public User UpdatedBy { get; set; }
}

用户.cs

public class User
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

SupplierDto.cs

public class SupplierDto
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Cnpj { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
    public long CreatedById { get; set; }
    public string CreatedByName { get; set; }
}

这是我将 SupplierDto 映射到 Supplier 的代码:

var configuration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<SupplierDto, Supplier>();
});

var mapper = new Mapper(configuration);

var dto = new SupplierDto
{
    Id = 1,
    Name = "Supplier One",
    CreatedById = 2,
    CreatedByName = "John Doe",
    CreatedAt = DateTime.Now,
    UpdatedAt = DateTime.Now,
};

var supplier = mapper.Map<Supplier>(dto);

//supplier.CreatedBy is null here
Console.WriteLine(supplier?.CreatedBy?.Name);

我想要达到的结果是这样的:

var supplier = new Supplier {
    Id = dto.Id,
    Name = dto.Name,
    CreatedAt = dto.CreatedAt,
    UpdatedAt = dto.UpdatedAt,
    CreatedBy = new User
    {
      Id = dto.CreatedById, 
      Name = dto.CreatedByName
    }
}

AutoMapper 为IdNameCreatedAtUpdatedAt道具执行 map ,但不会为CreatedBy道具创建新的User

我缺少什么?

首先,没有配置验证的 AM 很难使用。 所以这样做:)

然后,正如文档所说,您需要ReverseMap来展开。

c.CreateMap<Supplier, SupplierDto>().ForMember(d=>d.Cnpj, o=>o.Ignore()).ReverseMap();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM