AutoMapper map custom value ForMember

Viewed 2264

I'm using AutoMapper 8.1.1

How to assign a value for destination member but not from source.

I have this code`

    public IEnumerable<PartsTreeVM> GetMainPartsCategories(int type)
    {
        var model = _db.GetALLPartCategoriesTreeWithImages(type, 25);
        var mapper = new MapperConfiguration(cfg => cfg.CreateMap<GetALLPartCategoriesTreeWithImages_Result, PartsTreeVM>()
                .ForMember(dest => dest.VehicleType, opt => opt.MapFrom(type))
            )
            .CreateMapper();
        var result = mapper.Map<List<PartsTreeVM>>(model);

        return result;
    }

I want int type parameter to be assigned to all dest.VehicleType member.

2 Answers

How to assign a value for destination member but not from source.

You can use an AfterMap to ensure the target destination field is present.

.ForMember(...)
.ForMember(...)
.AfterMap((source, destination) => { /*do whatever you like with destination :-) */ });

Or if it's static data:

.ForMember(dest => dest.VehicleType, c => c.MapFrom((s => type));

You could try this:

var model = _db.GetALLPartCategoriesTreeWithImages(type, 25);
        var mapper = new MapperConfiguration(cfg => cfg.CreateMap<GetALLPartCategoriesTreeWithImages_Result, PartsTreeVM>()
                .ForMember(dest => dest.VehicleType, opt => opt.MapFrom(s => type))
            )
            .CreateMapper();

Or you could use AfterMap for sampleYou could try this:

var model = _db.GetALLPartCategoriesTreeWithImages(type, 25);
        var mapper = new MapperConfiguration(cfg => cfg.CreateMap<GetALLPartCategoriesTreeWithImages_Result, PartsTreeVM>()
                .AfterMap((s, d) => {
                    d.VehicleType = type;
                }) 
            )
            .CreateMapper();
Related