1

我有这张地图:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Sistema.DataEntities.Models.Cliente, CadastroModule.Model.Cliente>().ReverseMap();
});

CadastroModule.Model.Cliente (MVVM 模型):

public class Cliente
{
    public int ClienteID { get; set; }
    public string Nome { get; set; }
    public string EnderecoCEP { get; set;}
    public string EnderecoBairro { get; set; }
    public string EnderecoLogradouro { get; set; }
    public int EnderecoNumero { get; set; }
    public string EnderecoComplemento { get; set; }
}

Sistema.DataEntities.Models (POCO):

public class Cliente : Entity
{
    public Cliente()
    {
        Endereco = new Endereco();
    }

    public int ClienteID { get; set; }

    public string Nome { get; set; }

    public Endereco Endereco { get; set; }//1 pra 1 (Complex type EF)
}

Sistema.DataEntities.Models (POCO):

public class Endereco : Entity
{
    public string CEP { get; set; }
    public string Bairro { get; set; }
    public string Logradouro { get; set; }
    public int Numero { get; set; }
    public string Complemento { get; set; }

}

当我尝试它时它完美运行:

var t = _clienteService.ClienteService_GetAll().Project().To<Cliente>();

但是当我需要回到 poco 时,我遇到了麻烦:

Sistema.DataEntities.Models.Cliente clifinal = Mapper.Map<Cliente, Sistema.DataEntities.Models.Cliente>(ObCliente);

我的结果:

在此处输入图像描述

为什么 Endereco 对象具有空值?

4

1 回答 1

1

Automapper 不是为“展开”对象而构建的。您的模型 --> 视图模型映射按惯例工作;目标中的“Endereco”前缀告诉 AutoMapper 查看嵌套对象。

要让它以另一种方式工作,您必须手动添加一个映射 from CadastroModule.Model.Clienteto Sistema.DataEntities.Models.Endereco,然后在反向映射 from CadastroModule.Model.Clienteto中使用该映射Sistema.DataEntities.Models.Cliente

cfg.CreateMap<Cliente, CadastroModule.Model.Cliente>()
    .ReverseMap()
    // Map the `Endereco` property from `Cliente`
    .ForMember(dest => dest.Endereco, opt => opt.MapFrom(src => src));

cfg.CreateMap<CadastroModule.Model.Cliente, Endereco>();
    .ForMember(dest => dest.Bairro, opt => opt.MapFrom(src => src.EnderecoBairro))
    .ForMember(dest => dest.CEP, opt => opt.MapFrom(src => src.EnderecoCEP))
    .ForMember(dest => dest.Complemento, opt => opt.MapFrom(src => src.EnderecoComplemento))
    .ForMember(dest => dest.Logradouro, opt => opt.MapFrom(src => src.EnderecoLogradouro))
    .ForMember(dest => dest.Numero, opt => opt.MapFrom(src => src.EnderecoNumero));

Endereco您可以注册Endereco为源前缀,而不是映射 的每个属性:

cfg.CreateMap<Cliente, CadastroModule.Model.Cliente>()
    .ReverseMap()
    .ForMember(dest => dest.Endereco, opt => opt.MapFrom(src => src));

cfg.RecognizePrefixes("Endereco");
cfg.CreateMap<CadastroModule.Model.Cliente, Endereco>();

提出的这个解决方案,我认为作者关于双向映射的帖子值得一读。本质上,AutoMapper 并不是为了映射域实体而构建的。当然,您可以随心所欲地使用它,但这可能解释了为什么不支持开箱即用的这种场景。

于 2014-08-21T21:06:17.427 回答