繁体   English   中英

如何使用automapper将源类型的Parent映射到目标类型的集合?

[英]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 DestinationUserDestination类中有很多种情况。 换句话说,每个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了。

事实证明我距离我所追求的解决方案只有一步之遥。 SourceUserDestinationUser类的映射扩展为如下所示:

Mapper.CreateMap<SourceUser, DestinationUser>()
                .AfterMap((source, destination) => Mapper.Map<Source, List<Destination>>(source.Source, destination.Destinations));

希望这可以帮助某人,遇到类似的问题,我面临的问题:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM