Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
904 views
in Technique[技术] by (71.8m points)

asp.net mvc - Automapper map into nested class

I have 1 class that I need t map into multiple classes, for eg.

This is the source that I'm mapping from(view model):

public class UserBM
{
    public int UserId { get; set; }

    public string Address { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    public string State { get; set; }

    public int CountryId { get; set; }
    public string Country { get; set; }
}

This is how the destination class is(domain model):

public abstract class User
{
    public int UserId { get; set; }

    public virtual Location Location { get; set; }
    public virtual int? LocationId { get; set; }
}

public class Location
{
    public int LocationId { get; set; }

    public string Address { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    public string State { get; set; }

    public virtual int CountryId { get; set; }
    public virtual Country Country { get; set; }

}

This is how my automapper create map currently looks:

Mapper.CreateMap<UserBM, User>();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Define two mappings, both mapping from the same source to different destinations. In the User mapping, map the Location property manually using Mapper.Map<UserBM, Location>(...)

Mapper.CreateMap<UserBM, Location>();
Mapper.CreateMap<UserBM, User>()
    .ForMember(dest => dest.Location, opt => 
         opt.MapFrom(src => Mapper.Map<UserBM, Location>(src));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...