自动映射器。覆盖默认约定

时间:2018-12-23 17:12:00

标签: .net automapper

假设我具有以下配置

public class Source
{
    public Guid Id { get; set; }
    public Guid EntityId { get; set; }
}

public class Destination
{
    public Guid Id { get; set; }
}

我需要做的是将Source.EntityId映射到DestinationId。但是只有

CreateMap<Source, Destination>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(s => s.EntityId))

不能解决问题。它继续将Source.Id映射到Destination.Id。我该怎么做才能覆盖这种行为?

2 个答案:

答案 0 :(得分:0)

问题出在建设者身上,我没有引起足够的重视

public class Destination
{
    public Destination(Guid id)
    {
        Id = id;
    }

    public Guid Id { get; set; }
}

因此,它尝试使用构造函数进行 Id 字段初始化。这样解决:

CreateMap<Source, Destination>()
.ForCtorParam("id", opt=> opt.MapFrom(s => s.EntityId));

答案 1 :(得分:0)

public class AutoMapperConfig
{
    public static void Register(IServiceCollection services)
    {
        var config = new AutoMapper.MapperConfiguration(cfg => {
            cfg.AddProfile<MappingProfile>(); 
        });
        var mapper = config.CreateMapper();
        Mapper.Initialize(cfg=>cfg.AddProfile<MappingProfile>());
        services.AddSingleton(mapper);

    }
}

和Startup.cs

  public void ConfigureServices(IServiceCollection services)
        {
           ....
            AutoMapperConfig.Register(services);
            ....   
        }

并创建MappingProfile.cs

 public class MappingProfile : Profile
    {   
        public MappingProfile()
        {
          CreateMap<Source, Destination>()
            .ForMember(dest => dest.Id, opt => opt.MapFrom(s => s.EntityId))
        }
    }