简体   繁体   English

AutoMapper map 自定义值 ForMember

[英]AutoMapper map custom value ForMember

I'm using AutoMapper 8.1.1我正在使用 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.我希望将 int 类型参数分配给所有 dest.VehicleType 成员。

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.您可以使用AfterMap来确保存在目标目标字段。

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

Or if it's static data:或者如果是 static 数据:

.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:或者你可以使用AfterMap作为示例你可以试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM