Automapper:继承映射不包括扁平化属性
创始人
2024-09-23 11:30:46
0

使用Automapper进行继承映射时,如果想要排除扁平化属性,可以通过自定义解析器来实现。以下是一个示例代码:

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Child : Parent
{
    public string ChildProperty { get; set; }
}

public class ParentDto
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ChildDto : ParentDto
{
    public string ChildProperty { get; set; }
}

public class CustomMappingProfile : Profile
{
    public CustomMappingProfile()
    {
        CreateMap();

        CreateMap()
            .IncludeBase()
            .ForMember(dest => dest.ChildProperty, opt => opt.Ignore());
    }
}

public class MappingService
{
    private IMapper _mapper;

    public MappingService()
    {
        var mappingConfig = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile();
        });

        _mapper = mappingConfig.CreateMapper();
    }

    public ChildDto MapChildToChildDto(Child child)
    {
        return _mapper.Map(child);
    }
}

在上面的示例中,我们定义了一个父类Parent和一个继承自Parent的子类Child。我们还定义了相应的DTO类ParentDtoChildDto

然后,我们创建了一个自定义的CustomMappingProfile,在其中定义了映射规则。对于ChildChildDto的映射,我们使用IncludeBase方法来包含父类的映射规则,并使用ForMember方法来排除扁平化属性ChildProperty

最后,我们在MappingService中初始化CustomMappingProfile并使用IMapper接口进行映射操作。在MapChildToChildDto方法中,我们传入一个Child对象并使用_mapper.Map方法将其映射为ChildDto对象。

这样,当我们调用MapChildToChildDto方法时,Automapper会根据我们定义的映射规则进行映射,并排除ChildDto中的扁平化属性ChildProperty

相关内容

热门资讯

教程攻略"福建十三水... 您好:这款福建十三水辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款福建十三水辅助游戏中打牌都会发...
新手必备"天蝎辅助&... 新手必备"天蝎辅助"开挂(透视)wepoker轻量版辅助(有挂技术)wepoker轻量版辅助ai黑科...
玩家必看教程"斗棋联... 玩家必看教程"斗棋联盟俱乐部辅助挂"开挂(透视)hhpoker怎么防作弊(有挂攻略)1、下载安装好斗...
透视计算"开心酷跑破... 开心酷跑破解版 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、...
总算了解"白银胡乐亲... 白银胡乐亲友房开挂教程视频分享装挂详细步骤在当今的网络游戏中,白银胡乐亲友房作为一种经典的娱乐方式,...
记者爆料"玄龙辅助工... 您好:wepoker透视底牌脚本这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很...
实操分享"葫芦娃七子... 实操分享"葫芦娃七子降妖破解版内购"开挂(透视)德扑圈透视(讲解有挂)1、下载安装好葫芦娃七子降妖破...
一分钟教会你"宝宝浙... 一分钟教会你"宝宝浙江游戏有没有辅助器"开挂(透视)wpk俱乐部辅助器(有挂解惑);无需打开直接搜索...
交流学习经验"多乐够... 交流学习经验"多乐够级辅助软件"开挂(透视)we poker游戏下(有挂技巧)《详细加薇136704...
大神推荐"打两圈兴化... 大神推荐"打两圈兴化辅助"开挂(透视)we-poker靠谱吗(有挂头条)1、下载安装好打两圈兴化辅助...