简体   繁体   English

如何使用 AutoMapper 进行嵌套映射?

[英]How to do nested mapping with AutoMapper?

I have an entity and model defined as this:我有一个实体和模型定义如下:

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }   
    public string LastName { get; set; }    
    public Location Location { get; set; }            
    public string Gender { get; set; }    
    public string Skills { get; set; }    
    public bool isPrivate { get; set; }
}

public class Location
{
    public int Id { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Location Location { get; set; }
    public bool isPrivate { get; set; }
}

Then, I have setup a mapping profile defined as this:然后,我设置了一个定义如下的映射配置文件:

public MappingProfile()
{
    CreateMap<User, UserModel>()
        .ReverseMap();
}

And the point is that this works to some extend, but the Location complex type is not mapped properly.关键是这在某种程度上是有效的,但是Location复杂类型没有正确映射。 I can always flatten it, by including LocationCity and LocationCountry inside the UserModel class, but that's not what I wanna do.我总是可以通过在UserModel类中包含LocationCityLocationCountry来将其展平,但这不是我想要做的。 I want Location to appear as a nested property in the returned result, as it is defined originally.我希望Location在返回的结果中显示为嵌套属性,因为它最初是定义的。 How can I achieve this in AutoMapper?如何在 AutoMapper 中实现这一点?

You need to add a mapping between Location to Location too.您还需要添加位置到位置之间的映射。 Yep, the source and destination are identitic.是的,源和目标是相同的。

So your mapping profile should look like this:因此,您的映射配置文件应如下所示:

public MappingProfile()
{
    CreateMap<Location, Location>();
    CreateMap<User, UserModel>()
        .ReverseMap();
}

You could define your configuration like this:你可以这样定义你的配置:

 CreateMap<User, UserModel>()
     .ForMember(um => um.Location , opt => opt.MapFrom(u => u.Location))
     .ReverseMap();

The ReverseMap can only create a simple mapping. ReverseMap只能创建一个简单的映射。 For any complex type, you need to configure it manually, because AutoMaper don't know exactly how to instantiate the Location property and it will return null reference.对于任何复杂类型,都需要手动配置,因为 AutoMaper 并不确切知道如何实例化Location属性,它会返回null引用。

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

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