我有这张地图:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Sistema.DataEntities.Models.Cliente, CadastroModule.Model.Cliente>().ReverseMap();
});
CadastroModule.Model.Cliente(MVVM MODEL):
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对象具有空值?
答案 0 :(得分:1)
Automapper并没有为&#34; unflattening&#34;而建立。对象。你的模特 - &gt; ViewModel映射按惯例工作; &#34; Endereco&#34;目标中的前缀告诉AutoMapper查看嵌套对象。
要让其他方式工作,您必须手动从CadastroModule.Model.Cliente
添加映射到Sistema.DataEntities.Models.Endereco
,然后在CadastroModule.Model.Cliente
的反向映射中使用该映射到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>();
提出此解决方案,我认为the author's post on two way mapping值得一读。从本质上讲,AutoMapper不是为将映射回域实体而构建的。当然,您可以随意使用它,但这可以解释为什么这种情况不支持开箱即用。