How to automap this(mapping sub members)

前端 未结 4 1994
春和景丽
春和景丽 2021-01-17 13:52

I have something like this

public class ProductViewModel
{
  public int SelectedProductId { get; set; }
  public string ProductName {get; set;}
  public int          


        
4条回答
  •  自闭症患者
    2021-01-17 14:10

    To Map nested structures, you just need to create a new object in the MapFrom argument.

    Example

    Mapping:

    Mapper.CreateMap()
          .ForMember(d => d.MyNestedType, o => o.MapFrom(t => new NestedType { Id = t.Id }));
    Mapper.AssertConfigurationIsValid();
    

    Test Code:

    var source = new Source { Id = 5 };
    var destination = Mapper.Map(source);
    

    Classes:

    public class Source
    {
        public int Id { get; set; }
    }
    
    public class Destination
    {
        public NestedType MyNestedType { get; set; }
    }
    
    public class NestedType
    {
        public int Id { get; set; }
    }
    

提交回复
热议问题