Automapper多对多映射,包括关联表数据。
创始人
2024-09-23 12:30:25
0

AutoMapper是一个用于对象映射的开源库,可以简化对象之间的转换。在多对多映射中,包含关联表数据时,我们可以使用AutoMapper的ForMember方法来配置映射。

以下是一个使用AutoMapper进行多对多映射的代码示例:

  1. 首先,我们需要定义两个实体类,分别是源实体类和目标实体类,以及它们之间的关联实体类。
public class SourceEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection Destinations { get; set; }
}

public class DestinationEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection Sources { get; set; }
}

public class SourceDestinationAssociation
{
    public int SourceEntityId { get; set; }
    public int DestinationEntityId { get; set; }
}

public class DestinationSourceAssociation
{
    public int DestinationEntityId { get; set; }
    public int SourceEntityId { get; set; }
}

  1. 接下来,我们需要创建映射配置类,其中定义了源实体类到目标实体类的映射关系。
public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap()
            .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
            .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
            .ForMember(dest => dest.Sources, opt => opt.MapFrom(src => src.Destinations.Select(d => new DestinationSourceAssociation { DestinationEntityId = d.DestinationEntityId, SourceEntityId = src.Id })));

        CreateMap()
            .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
            .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
            .ForMember(dest => dest.Destinations, opt => opt.MapFrom(src => src.Sources.Select(s => new SourceDestinationAssociation { SourceEntityId = s.SourceEntityId, DestinationEntityId = src.Id })));
    }
}
  1. 在使用映射之前,需要先初始化AutoMapper,并注册映射配置类。
Mapper.Initialize(cfg => cfg.AddProfile());
  1. 最后,我们可以使用AutoMapper进行多对多映射。
var sourceEntity = new SourceEntity
{
    Id = 1,
    Name = "Source Entity",
    Destinations = new List
    {
        new SourceDestinationAssociation { DestinationEntityId = 1 },
        new SourceDestinationAssociation { DestinationEntityId = 2 }
    }
};

var destinationEntity = Mapper.Map(sourceEntity);

在上面的示例中,我们通过映射配置类将源实体类SourceEntity映射到目标实体类DestinationEntity,并且包含了关联表数据。在映射配置中,我们使用ForMember方法来指定每个属性的映射关系,包括多对多关联关系的映射。

相关内容

热门资讯

透视有挂!wepoker底牌透... 透视有挂!wepoker底牌透视(透视)其实有挂(详细辅助攻略方法)1、下载好辅助软件之后点击打开,...
必看攻略!impoker辅助,... 必看攻略!impoker辅助,uupoker有透视吗,线上教程(有挂透视)1、很好的工具软件,可以解...
透视数据!拱趴大菠萝作弊方法(... 透视数据!拱趴大菠萝作弊方法(透视)确实真的是有挂(详细辅助解密教程)1、每一步都需要思考,不同水平...
重大消息!pokerworld... 1、重大消息!pokerworld软件,hhpoker是正规的吗,大神讲解(有挂辅助);详细教程。2...
透视ai代打!hhpoker智... 透视ai代打!hhpoker智能辅助插件(透视)真是真的有挂(详细辅助新2025教程)1、点击下载安...
安装程序教程!hh poker... 安装程序教程!hh poker辅助器先试用,德州透视是真的吗,透视教程(有挂神器)这是由厦门游乐互动...
透视ai代打!wepoker黑... 透视ai代打!wepoker黑侠辅助器(透视)切实真的有挂(详细辅助可靠教程)1、ai机器人多个强度...
2024教程!拱趴大菠萝开挂方... 2024教程!拱趴大菠萝开挂方法,wepoker辅助器安装包定制,插件教程(有挂技巧)1、点击下载安...
盘点一款!we-poker有人... 盘点一款!we-poker有人玩吗,wepoker透视脚本网页,玩家教程(有挂攻略);支持多人共享记...
透视了解!we poker插件... 透视了解!we poker插件(透视)好像有挂(详细辅助存在挂教程);1、系统规律教程、辅助透视等服...