简体   繁体   English

自动映射器:展平

[英]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: 我已经尝试了所有从Item类映射到ItemDto类的映射(基本上是扁平化的映射),但是我一直为ItemDto.NestedItemName获取null:

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. 但它返回null。 Any ideas? 有任何想法吗? I'm using AutoMapper 7.0.1 in a .Net Core 2.1 app. 我在.Net Core 2.1应用中使用了AutoMapper 7.0.1。

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 很有可能是将项目转换为dto,因此应使用该地图创建地图

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 不需要自定义映射,默认的命名约定涵盖了此内容。

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

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