Using ValueInjecter to map between objects with different property names

前端 未结 2 518
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 06:41

How do I map a property from an object to another object with a different property name?

I have a Product class that looks like this:

public         


        
2条回答
  •  忘掉有多难
    2021-02-06 07:41

    You can do this easily with AutoMapper. By default is uses convention (i.e. Id maps to Id and Name to Name), but you can also define custom mappings.

    Mapper.CreateMap()
        .ForMember(destination => destination.ProductName,
                   options => options.MapFrom(
                        source => source.Name));
    

    Your contoller mapping code will be then this simple :

    Mapper.Map(product, viewModel);
    

提交回复
热议问题