AutoMapper从其父属性映射集合属性值。
创始人
2024-09-23 12:00:24
0

在使用AutoMapper进行映射时,可以使用ForMember方法来自父属性映射集合属性值。下面是一个示例代码:

using AutoMapper;
using System;
using System.Collections.Generic;

public class SourceParent
{
    public List Children { get; set; }
}

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

public class DestinationParent
{
    public List Children { get; set; }
}

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

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

public class Program
{
    public static void Main()
    {
        var configuration = new MapperConfiguration(cfg => {
            cfg.AddProfile();
        });
        var mapper = configuration.CreateMapper();

        var sourceParent = new SourceParent
        {
            Children = new List
            {
                new SourceChild { Name = "Child 1" },
                new SourceChild { Name = "Child 2" },
                new SourceChild { Name = "Child 3" }
            }
        };

        var destinationParent = mapper.Map(sourceParent);

        foreach (var child in destinationParent.Children)
        {
            Console.WriteLine(child.Name);
        }
    }
}

在上面的代码中,我们定义了SourceParentDestinationParent类作为源对象和目标对象,它们都包含一个名为Children的集合属性。我们还定义了SourceChildDestinationChild类作为集合中的子对象。

MappingProfile类中,我们使用CreateMap方法创建了源对象和目标对象之间的映射关系。我们使用ForMember方法指定了SourceParent.Children属性映射到DestinationParent.Children属性,并且两者具有相同的名称。

Main方法中,我们首先创建了MapperConfiguration实例,并将MappingProfile添加到配置中。然后我们使用配置创建了IMapper实例。接下来,我们创建了源对象sourceParent,并使用mapper.Map方法进行映射,将其转换为目标对象destinationParent。最后,我们遍历destinationParent.Children并打印每个子对象的名称。

运行以上代码,输出结果将会是:

Child 1
Child 2
Child 3

可以看到,我们成功地将源对象的集合属性值映射到了目标对象的集合属性中。

相关内容

热门资讯

透视脚本(wepoKe)wpk... 透视脚本(wepoKe)wpk的发牌有规律吗(透视)详细辅助新2025教程;小薇(透视辅助)致您一封...
辅助透视!约局吧开挂(透视)本... 1、辅助透视!约局吧开挂(透视)本然真的是有挂(详细辅助科技教程)2、进入游戏-大厅左侧-新手福利-...
透视透视挂!wpk辅助软件(透... 透视透视挂!wpk辅助软件(透视)详细辅助我来教教你(其实真的是有挂)1、wpk辅助软件系统规律教程...
透视好友房(wePoKe)德州... 透视好友房(wePoKe)德州ai机器人辅助(透视)详细辅助切实教程;建议优先通过德州ai机器人辅助...
透视肯定!hhpoker作弊实... 透视肯定!hhpoker作弊实战视频(透视)一直存在有挂(详细辅助2025新版技巧)是一款可以让一直...
透视安卓版!wepoker辅助... 透视安卓版!wepoker辅助下载(透视)详细辅助新2025版(总是有挂)1、不需要AI权限,帮助你...
透视了解(wepOke)wpk... 透视了解(wepOke)wpk免费赛规则(透视)详细辅助黑科技教程,支持语音通讯、好友开房及战队组建...
透视黑科技!hhpoker德州... 透视黑科技!hhpoker德州作弊(透视)从前真的有挂(详细辅助软件教程);hhpoker德州作弊软...
透视玄学!智星德州有脚本吗(透... 透视玄学!智星德州有脚本吗(透视)详细辅助曝光教程(竟然是有挂)1、用户打开应用后不用登录就可以直接...
透视透视挂(Wepoke)wp... 透视透视挂(Wepoke)wpk辅助神器(透视)详细辅助透明教程;玩家必备必赢加哟《13670430...