AutoMapper是一个用于对象映射的开源库,可以简化对象之间的转换。在多对多映射中,包含关联表数据时,我们可以使用AutoMapper的ForMember
方法来配置映射。
以下是一个使用AutoMapper进行多对多映射的代码示例:
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; }
}
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 })));
}
}
Mapper.Initialize(cfg => cfg.AddProfile());
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
方法来指定每个属性的映射关系,包括多对多关联关系的映射。