0

Is it possible to tell AutoMapper during map creating to map onto existing instance of nested property?

Let's suppose I've got a class:

public class SomeClass
{
    public int Id {get; set;}
    public Complex Settings {get; set;}

}

public class Complex
{
    public int Id { get; set;}
    public string SomeText { get; set;}
}

I want to create map from SomeClass to SomeClass and use it to map properties onto existing instance.

Mapper.CreateMap<SomeClass, SomeClass>()
    .ForMember(src => src.Settings, opts => opts.MapFrom(src => Mapper.Map<Complex, Complex>(src));

Mapper.CreateMap<Complex, Complex>();

Mapper.Map<SomeClass, SomeClass>(a, b);

Where a and b are instances of SomeClass. The problem is this solution maps properties onto existing instance but creates new instance of Complex instead of mapping a.Complex onto existing b.Complex.

Is it possible to configure AutoMapper to get desired behavior?

(It's causing me a lot of problems with Entity Framework).

0xced
  • 25,219
  • 10
  • 103
  • 255
user2184057
  • 924
  • 10
  • 27
  • 1
    Possible duplicate of [How do you map a Dto to an existing object instance with nested objects using AutoMapper?](http://stackoverflow.com/questions/3672447/how-do-you-map-a-dto-to-an-existing-object-instance-with-nested-objects-using-au) – MisterIsaak Aug 25 '16 at 20:06

1 Answers1

4

I figured it out myself. Solution was pretty simple.

Correct map creation looks like this:

Mapper.CreateMap<SomeClass, SomeClass>()
.ForMember(src => src.Settings, opts => opts.Ignore())
.AfterMap((src, dst) => Mapper.Map<TestSettings,TestSettings>(src.TestSettings, dst.TestSettings); 

Mapper.CreateMap<Complex, Complex>();
user2184057
  • 924
  • 10
  • 27