Automapper от плоской модели до нескольких сложных свойств одного типа - PullRequest
0 голосов
/ 22 ноября 2018

Есть ли способ заставить autopper отображать следующее без необходимости сопоставлять каждое свойство или создавать разные модели представления для каждого адреса?

Источник:

public class ViewModel
{
    public decimal? BillingAddressLatitude { get; set; }
    public string BillingAddressLine1 { get; set; }
    public string BillingAddressLine2 { get; set; }
    public string BillingAddressLine3 { get; set; }
    public decimal? BillingAddressLongitude { get; set; }
    public string BillingAddressPostalCode { get; set; }
    public string BillingAddressUnit { get; set; }
    public long? MailingAddressCityId { get; set; }
    public decimal? MailingAddressLatitude { get; set; }
    public string MailingAddressLine1 { get; set; }
    public string MailingAddressLine2 { get; set; }
    public string MailingAddressLine3 { get; set; }
    public decimal? MailingAddressLongitude { get; set; }
    public string MailingAddressPostalCode { get; set; }
    public string MailingAddressUnit { get; set; }
    public string Name { get; set; }
}

Направления:

public class Model
{
    public Address BillingAddress { get; set; }
    public Address MailingAddress { get; set; }
    public string Name { get; set; }
}

public class Address
{
    public decimal? Latitude { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string Line3 { get; set; }
    public decimal? Longitude { get; set; }
    public string PostalCode { get; set; }
    public string Unit { get; set; } 
}

Это была моя попытка карты.

CreateMap<ViewModel, Address>();
CreateMap<ViewModel, Model>()
    .ForMember(d => d.BillingAddress, o => o.MapFrom(s => s))
    .ForMember(d => d.MailingAddress, o => o.MapFrom(s => s));

При этом инициализируются оба адреса, но свойства всегда равны нулю.

Если в любой конфигурации нет автоматического заполнения этих свойств, я приму поражение и сопоставлю каждое свойствоиндивидуально.

Спасибо за ваш вклад.

1 Ответ

0 голосов
/ 22 ноября 2018

Это работает

Отображения

public class ReverseMappingProfile : Profile
{
    public ReverseMappingProfile()
    {
        RecognizeDestinationPrefixes("Billing", "Mailing");

        CreateMap<Model, ViewModel>()
            .ReverseMap();
        CreateMap<Address, ViewModel>()
            .ReverseMap();
    }
}

Конфиг

var mappingConfig = new MapperConfiguration(mc =>
{
   mc.AddProfile(new ReverseMappingProfile());
});

IMapper mapper = mappingConfig.CreateMapper();

Выполнение

var model = new Model
{
    Name = "Joe Bloggs",
    BillingAddress = new Address
    {
        Line1 = "Line 1",
        Line2 = "Line 1",
        Line3 = "Line 1",
        PostalCode = "ABCDEF",
        Latitude = 1232,
        Longitude = 4321,
        Unit = "A Unit"
    },
    MailingAddress = new Address
    {
        Line1 = "M Line 1",
        Line2 = "M Line 1",
        Line3 = "M Line 1",
        PostalCode = "MMFDS",
        Latitude = 6543,
        Longitude = 78990,
        Unit = "M Unit"
    },
};

var viewModel = mapper.Map<ViewModel>(model);

var newModel = mapper.Map<Model>(viewModel);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...