繁体   English   中英

Map 与 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;}
}

我想把 map 这个变成

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
    })));

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

暂无
暂无

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

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