[英]How can I use Automapper to map an object to an unknown destination type?
[英]How to use automapper to map Parent of source type into a collection of destination type?
我有这些课程:
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; }
}
我使用这些映射映射这些类:
Mapper.CreateMap<SourceChild, Destination>()
.ForMember(item => item.ID, property => property.MapFrom(item => item.SourceId))
.ForMember(item => item.Age, property => property.MapFrom(item => item.Source.Age));
Automapper自动映射其他两个属性。 因此,如果我尝试将SourceChild
映射到Destination
类型,一切正常。 但是现在我有另一个使用源和目标类型的类:
public class SourceUser
{
public string ID { get; set; }
public virtual Source Source { get; set; }
}
public class DestinationUser
{
public string Id { get; set; }
public List<Destination> Destinations { get; set; }
}
为了更好地说明这种情况,这里是对类的简短描述:我有Source
对象和SourceChild
子对象。 SourceChild
对象包含不同语言的信息。 当我将Source映射到Destination
我想输入Source对象并接收目标对象集合的输出。 对于Source
对象的每个SourceChild
对象,应该有一个Destination
对象。 SourceUser
简单地引用具有1-many关系的Source
。 DestinationUser
在Destination
类中有很多种情况。 换句话说,每个DestinationUser
都有一个所有语言的所有Destinations
的列表。 所以考虑到这一切让我们回到代码中。
我在编写我需要的代码时运气不错。 我想出了这个:
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));
这个ALMOST工作得很好,但有一个IF。 我正在使用可查询扩展来处理映射。 当我检索DestinationUsers
的集合时,它们都没有映射Destinations
属性。 它显示为null。 但是,如果我像这样手动进行映射:
SourceUser SourceUser = Db.GetSourceUser();
DestinationUser DestUser = Db.GetDestinationUser();
DestUser.Destinations = Mapper.Map<List<Destination>>(SourceUser.Source);
everythign工作正常。 DestinationUsers列表从Source实例映射。
是否有可能避免手动调用后者Mapper.Map()
调用? 还要记住,列表目的地可以更改为任何其他集合。 我只是想为每个目标对象SourceChild
对象Source
了。
事实证明我距离我所追求的解决方案只有一步之遥。 我SourceUser
和DestinationUser
类的映射扩展为如下所示:
Mapper.CreateMap<SourceUser, DestinationUser>()
.AfterMap((source, destination) => Mapper.Map<Source, List<Destination>>(source.Source, destination.Destinations));
希望这可以帮助某人,遇到类似的问题,我面临的问题:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.