AutoMapper and “UseDestinationValue”

帅比萌擦擦* 提交于 2019-12-05 08:04:52
Vaccano

I wrote this whole question up and then thought, DUH! just run it and see.

It works as I had hoped.

This is the code I ended up with:

class Program
{
    static void Main(string[] args)
    {
        PersonContract personContract = new PersonContract {NickName = "Dan"};
        Person person = new Person {Name = "Robert", NickName = "Bob"};
        Mapper.CreateMap<PersonContract, Person>()
            .ForMember(x => x.Name, opt =>
                                        {
                                            opt.UseDestinationValue();
                                            opt.Ignore();
                                        });

        Mapper.AssertConfigurationIsValid();

        var personOut = 
            Mapper.Map<PersonContract, Person>(personContract, person);

        Console.WriteLine(person.Name);
        Console.WriteLine(person.NickName);

        Console.WriteLine(personOut.Name);
        Console.WriteLine(personOut.NickName);
        Console.ReadLine();
    }
}

internal class Person
{
    public string Name { get; set; }
    public string NickName { get; set; }
}

internal class PersonContract
{
    public string NickName { get; set; }
}

The output was:

Robert
Dan
Robert
Dan

ZanderAdam

I was brought here having a similar question, but in regards to nested classes and keeping the destination value. I tried above in any way I could, but it did not work for me, it turns out you have to use UseDestinationValue on parent object as well. I am leaving this here in case anyone else has the same issue I did. It took me some time to get it working. I kept thinking the issue lies within AddressViewModel => Address mapping.

In BidderViewModel class, BidderAddress is of type AddressViewModel. I needed the Address ID to be preserved in situations where it is not null.

Mapper.CreateMap<BidderViewModel, Bidder>()
    .ForMember(dest => dest.BidderAddress, opt=> opt.UseDestinationValue())
    .ForMember(dest => dest.ID, opt => opt.UseDestinationValue());
Mapper.CreateMap<AddressViewModel, Address>()
    .ForMember(dest => dest.ID, opt => { opt.UseDestinationValue(); opt.Ignore(); });

Use (where viewModel is of type BidderViewModel as returned by the View in MVC):

Bidder bidder = Mapper.Map<BidderViewModel, Bidder>(viewModel, currentBid.Bidder)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!