Ivan Gritsenko
Ivan Gritsenko

Reputation: 4236

How to make Automapper use exact value without creating a new object

How to make Automapper use exact value without creating a new object?

using System.Collections.Generic;
using AutoMapper;

namespace Program
{
    public class A { }

    public class B
    {
        public A Aprop { get; set; }
    }

    public class C
    {
        public A Aprop { get; set; }
    }

    class Program
    {
        private static void Main(string[] args)
        {
            AutoMapper.Mapper.Initialize(cnf =>
            {
                // I really need this mapping. Some additional Ignores are present here.
                cnf.CreateMap<A, A>(); 
                // The next mapping should be configured somehow 
                cnf.CreateMap<B, C>(); //.ForMember(d => d.Aprop, opt => opt.MapFrom(...)) ???
            });
            A a = new A();
            B b = new B() {Aprop = a};
            C c = Mapper.Map<C>(b);
            var refToSameObject = b.Aprop.Equals(c.Aprop); // Evaluates to false
        }
    }
}

How should I change cnf.CreateMap<B, C>(); line in order to make refToSameObject variable have true value? If I remove cnf.CreateMap<A, A>(); it will work this way however I cannot remove it because sometimes I use automapper to update A classes from other A classes.

Upvotes: 1

Views: 632

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

One way around this is to use ConstructUsing and set Aprop during the construction of C:

AutoMapper.Mapper.Initialize(cnf =>
{
    cnf.CreateMap<A, A>(); 
    cnf.CreateMap<B, C>()
        .ConstructUsing(src => new C() { Aprop = src.Aprop })
        .ForMember(dest => dest.Aprop, opt => opt.Ignore());
});

This should work and isn't too painful assuming it's really just one property.

Upvotes: 1

Related Questions