Automapper - 将源子对象映射到目标时包含父级值
创始人
2024-09-23 08:30:44
0

在使用AutoMapper时,可以使用ForMember方法配置映射规则,以在源子对象映射到目标对象时包含父级值。下面是一个示例代码:

using AutoMapper;

public class ParentObject
{
    public int ParentValue { get; set; }
    public ChildObject Child { get; set; }
}

public class ChildObject
{
    public int ChildValue { get; set; }
}

public class DestinationObject
{
    public int ParentValue { get; set; }
    public int ChildValue { get; set; }
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap()
            .ForMember(dest => dest.ParentValue, opt => opt.MapFrom(src => src.ParentValue))
            .ForMember(dest => dest.ChildValue, opt => opt.MapFrom(src => src.Child.ChildValue));
    }
}

// 在代码的其他地方注册AutoMapper配置
public static class AutoMapperConfig
{
    public static void RegisterMappings()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile();
        });
    }
}

// 使用示例
var parent = new ParentObject
{
    ParentValue = 10,
    Child = new ChildObject
    {
        ChildValue = 20
    }
};

AutoMapperConfig.RegisterMappings();
var destination = Mapper.Map(parent);

Console.WriteLine($"ParentValue: {destination.ParentValue}");
Console.WriteLine($"ChildValue: {destination.ChildValue}");

在上面的示例中,我们定义了三个类:ParentObjectChildObjectDestinationObjectParentObject包含一个ChildObject子对象和一个ParentValue属性。ChildObject包含一个ChildValue属性。DestinationObject是我们希望映射到的目标类,它包含了ParentValueChildValue属性。

然后,我们创建了一个继承自ProfileMappingProfile类,并在其中配置了映射规则。使用ForMember方法,我们指定了如何映射ParentValueChildValue属性。opt.MapFrom方法允许我们指定从源对象到目标对象的映射方式。

在注册AutoMapper配置的AutoMapperConfig类中,我们使用Mapper.Initialize方法注册了MappingProfile

最后,在使用示例中,我们创建了一个源对象parent,并使用Mapper.Map方法将其映射到目标对象destination。我们可以通过打印目标对象的属性来验证映射结果。

输出结果将是:

ParentValue: 10
ChildValue: 20

这表明我们成功地将源子对象映射到了目标对象,并包含了父级值。

相关内容

热门资讯

普及知识!微信雀神麻将挂件开挂... 普及知识!微信雀神麻将挂件开挂辅助,微乐自建房脚本免费入口(开挂自建房)插件1、操作简单,无需微信雀...
一分钟揭秘!微乐家乡麻将自建房... 一分钟揭秘!微乐家乡麻将自建房辅助app,微乐自建房脚本免费入口(开挂自建房)脚本1、打开软件启动之...
热门推荐!微乐家乡麻将自建房辅... 热门推荐!微乐家乡麻将自建房辅助app,微乐家乡麻将自建房辅助app(开挂自建房)攻略1、微乐家乡麻...
发现一款!微乐自建房辅助工具,... 发现一款!微乐自建房辅助工具,微乐小程序免费黑科技(开挂自建房)软件1、全新机制【微乐自建房辅助工具...
揭秘一下!微乐家乡麻将自建房辅... 揭秘一下!微乐家乡麻将自建房辅助app,微乐自建房脚本免费入口(开挂自建房)攻略在进入微乐家乡麻将自...
分享给玩家!微乐自建房辅助工具... 分享给玩家!微乐自建房辅助工具挂,微乐小程序免费黑科技(开挂自建房)教程1、下载好微乐自建房辅助工具...
实测揭晓!微乐家乡麻将自建房辅... 实测揭晓!微乐家乡麻将自建房辅助app,微乐家乡麻将自建房辅助app(开挂自建房)插件1、进入游戏-...
终于知道!微信卡五星辅助器,微... 终于知道!微信卡五星辅助器,微乐小程序免费黑科技(开挂自建房)插件1、完成微信卡五星辅助器有辅助插件...
今日百科!微乐自建房辅助工具插... 今日百科!微乐自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)工具1、微乐自建房辅助工具插件...
最新通报!微乐家乡麻将自建房辅... 最新通报!微乐家乡麻将自建房辅助app,微乐家乡麻将自建房辅助app(开挂自建房)脚本1、不需要AI...