Home > OS >  How to map this using AutoMapper 11.0.0?
How to map this using AutoMapper 11.0.0?

Time:01-24

I have a model classes shown below.

    public class ModelA
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string DetailId{ get; set; }
        public string DetailName { get; set; }
        public string DetailDescription { get; set; }
    }

    public class ModelB
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

    public class ModelC
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public ModelB Detail { get; set; }
    }

Now, I want to map ModelA to ModelC where

  • DetailId = Detail.Id
  • DetailName = Detail.Name
  • DetailDescription = Detail.Description

Is this possible using Automapper 11.0.0 ? If possible, how ?

CodePudding user response:

Use this code:

CreateMap<ModelA, ModelC>()
    .ForMember(d => d.Detail.Id, src => src.MapFrom(e => e.DetailId))
    .ForMember(d => d.Detail.Description, src => src.MapFrom(e => e.DetailDescription))
    .ForMember(d => d.Detail.Name, src => src.MapFrom(e => e.DetailName))
    .ReverseMap();

CodePudding user response:

    var config = new MapperConfiguration(cfg => {
    cfg.CreateMap< ModelA, ModelC >().ForMember(u => u. Detail, o => o.MapFrom(s => s));
});

You want the modelB mapping in modelC,But the structure of modelA is different from that of modelC.

  •  Tags:  
  • Related