This is my source:
public class User
{
public int UserId { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Address { get; set; }
public string State {get; set; }
}
This is my destination:
public class UserVM
{
public int UserId { get; set; }
public string Address { get; set; }
public string State { get; set; }
}
How do I do the mapping? The normal create map doesn't work when they say flattening is automatic.
If you change your destination class property names to AddressStreet
and AddressState
, AutoMapper will, by convention, match them to Address.Street
and Address.State
on the source.
public class UserVM
{
public int UserId { get; set; }
public string AddressStreet { get; set; } // User.Address.Street
public string AddressState { get; set; } // User.Address.State
}
Alternatively, you leave your destination property names as is and use custom member mappings:
Mapper.CreateMap<User, UserVM>()
.ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street))
.ForMember(dest => dest.State, opt => opt.MapFrom(src => src.Address.State));
See the AutoMapper documentation for Projection and Flattening for more information.
I was stumped by this issue and this solved it for me. I assume in your code, AutoMapper is being injected by your DI container
public class MappingProfile: Profile
{
public MappingProfile()
{
CreateMap<User, UserVM>()
.IncludeMembers(u => u.Address);
CreateMap<Address, UserVM>();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With