Using ValueInjecter to map between objects with different property names

左心房为你撑大大i 提交于 2019-12-03 03:08:39
Chandermani

If you are using ValueInjecter then you would write a ConventionInjection. See the second sample here

    public class PropToTypeProp : ConventionInjection
    {
        protected override bool Match(ConventionInfo c)
        {
            return c.TargetProp.Name == c.Source.Type.Name + c.TargetProp.Name;
        }
    }

this injection will do from all properties of TSource.* to TTarget.TSource+*, so you do:

vm.InjectFrom<PropToTypeProp>(product);

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<Product, ProductSpecificationAddViewModel>()
    .ForMember(destination => destination.ProductName,
               options => options.MapFrom(
                    source => source.Name));

Your contoller mapping code will be then this simple :

Mapper.Map(product, viewModel);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!