C# 如何使用automapper将源类型的父级映射到目标类型的集合?
我有以下课程:C# 如何使用automapper将源类型的父级映射到目标类型的集合?,c#,automapper,C#,Automapper,我有以下课程: public class Source { public string ID { get; set; } public int Age Name { get; set; } public virtual ICollection<SourceChild> SourceChildren { get; set; } } public class SourceChild { public string Name { get; set; }
public class Source
{
public string ID { get; set; }
public int Age Name { get; set; }
public virtual ICollection<SourceChild> SourceChildren { get; set; }
}
public class SourceChild
{
public string Name { get; set; }
public string Language { get; set; }
public string SourceId { get; set; }
public virtual Source Source { get; set; }
}
public class Destination
{
public int Age { get; set; }
public string Name { get; set; }
public string Language { get; set; }
public string Id { get; set; }
}
为了更好地说明这种情况,这里对类进行了简短的描述:我有Source
对象和SourceChild
子对象SourceChild
对象包含不同语言的信息。当我将源映射到目标时,我想输入源对象并接收目标对象集合的输出。对于每个SourceChild
对象,Source
对象都应该有一个Destination
对象。SourceUser
仅指具有1-many关系的Source
DestinationUser
与Destination
类有多个retion。换句话说,每个DestinationUser
都有一个所有语言的所有目的地的列表。考虑到这些,让我们回到代码上来
我在编写我需要的代码方面运气不错。我想到了这个:
Mapper.CreateMap<SourceUser, DestinationUser>()
.AfterMap((source, destination) => Mapper.Map<Source, List<Destination>>(source.Source));
Mapper.CreateMap<Source, List<Destination>>()
.AfterMap((source, destination) => Mapper.Map<List<SourceChild>, List<Destination>>(source.SourceChildren.ToList(), destination));
一切都很好。DestinationUsers的列表是从源实例映射的
是否可以避免手动调用后者Mapper.Map()
call?还要记住,列表目的地可能会更改为任何其他集合。我只想为每个SourceChild
objectSource
had拥有一个目标对象 事实证明,我离我想要的解决方案只有一小步之遥。我所需要的只是扩展SourceUser
和DestinationUser
类的映射,使其如下所示:
Mapper.CreateMap<SourceUser, DestinationUser>()
.AfterMap((source, destination) => Mapper.Map<Source, List<Destination>>(source.Source, destination.Destinations));
Mapper.CreateMap()
.AfterMap((source,destination)=>Mapper.Map(source.source,destination.Destinations));
希望这能帮助那些遇到与我所面临的问题类似的问题的人:)事实证明,我离我所追求的解决方案只有一小步之遥。我所需要的只是扩展SourceUser
和DestinationUser
类的映射,使其如下所示:
Mapper.CreateMap<SourceUser, DestinationUser>()
.AfterMap((source, destination) => Mapper.Map<Source, List<Destination>>(source.Source, destination.Destinations));
Mapper.CreateMap()
.AfterMap((source,destination)=>Mapper.Map(source.source,destination.Destinations));
希望这有助于遇到与我所面临的问题类似的问题的人:)
SourceUser SourceUser = Db.GetSourceUser();
DestinationUser DestUser = Db.GetDestinationUser();
DestUser.Destinations = Mapper.Map<List<Destination>>(SourceUser.Source);
Mapper.CreateMap<SourceUser, DestinationUser>()
.AfterMap((source, destination) => Mapper.Map<Source, List<Destination>>(source.Source, destination.Destinations));