在 C# 中使用 Automapper 映射一对多关系

Map one-to-many relationship with Automapper in c#

如果我从数据库中获取如下所示:

SELECT * FROM Persons
JOIN Pet ON Person.Id = Pet.PersonId

假设这给出了 PersonWithPetsDataModel 的集合,其中有重复的人:

public class PersonWithPetsDataModel
{
    public Guid PersonId {get;set;}
    public string PersonName {get;set;}
    public Guid PetId {get;set;}
    public string PetName {get;set;}
}

我想将其映射到

public class Person
{
    public Guid PersonId {get;set;}
    public string PersonName {get;set;}
    public IEnumerable<Pet> Pets {get;set;}
}

public class Pet
{
    public Guid PetId {get;set;}
    public string PetName {get;set;}
}

如何使用自动映射器执行此操作?谢谢!

上面的评论让我找到了正确的方向,我想我明白了:

CreateMap<IEnumerable<PersonWithPetsDataModel>, Person>()
    .ForMember(x => x.PersonId, opt => opt.MapFrom(x => x.FirstOrDefault().PersonId))
    .ForMember(x => x.PersonName, opt => opt.MapFrom(x => x.FirstOrDefault().PersonName))
    .ForMember(x => x.Pets, opt => 
    opt.MapFrom(x => x.Select(y => new Pet
    {
        PetId = y.PetId
        PetName = y.PetName
    })));

感谢您的参与。也许这个答案将来会对其他人有所帮助。