简体   繁体   中英

Automapper: Flattening

I've tried everything to map from Item class to ItemDto class (basically a flattening map) but I keep getting a null for ItemDto.NestedItemName:

public class Item
{
    public NestedItem NestedItem{get;set;}
}

public class NestedItem
{
    public string Name{get;set;}
}

public class ItemDto
{
    public string NestedItemName{get;set;}
}

I would have thought this would work:

CreateMap<NestedItem, ItemDto>()
                .ForMember(dest => dest.NestedItemName, opt => opt.MapFrom(src => src.Name));

but it returns null. Any ideas? I'm using AutoMapper 7.0.1 in a .Net Core 2.1 app.

You are using the wrong mapping. More than likely it would be the item being converted to the dto so the map should be created using that

CreateMap<Item, ItemDto>()
    .ForMember(
        dest => dest.NestedItemName, 
        opt => opt.MapFrom(src => src.NestedItem.Name)
    );

From comments

There is be no need for the custom mapping, the default naming conventions covers this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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