Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper and "UseDestinationValue"

Tags:

automapper

What does UseDestinationValue do?

I am asking because I have a base and inherited class, and for the base class, I would love to have AutoMapper take existing values for me.

Will it do that? (I have looked and the only examples I can see for UseDestinationValue involve lists. Is it only for lists?

could I do this:

PersonContract personContract = new PersonContract {Name = 'Dan'};
Person person = new Person {Name = "Bob"};
Mapper.CreateMap<PersonContract, Person>()
      .ForMember(x=>x.Name, opt=>opt.UseDestinationValue());

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

Console.WriteLine(person.Name);

and have the output be bob?

like image 985
Vaccano Avatar asked Aug 16 '11 20:08

Vaccano


1 Answers

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

like image 185
Vaccano Avatar answered Oct 18 '22 06:10

Vaccano