3
votes

I have a source type which have simple properties and collection type properties. I have a destination type which have exactly the same simple properties and exactly the same collection type properties.

Edit: I forget to mention that the collection type properties not only the same names but actually the exact same types, regarding both the collection types, both the item types

After I configure one simple mapping for AutoMapper like:

Mapper.CreateMap<MySourceType, MyDestinationType>();

and map an instance:

var destination = Mapper.Map<MyDestinationType>(source);

it seems I got a deep copy. I would not to have a deep copy I would like the destination and source collection type properties just reference copied:

Assert.IsTrue(ReferenceEquals(destination.MyCollection, source.MyCollection));
1
You will only be able to do a shallow copy on types of common heritage. Also the point of AutoMapper is to do a deep copy. - tdbeckett
This smells like a lazy abuse of AutoMapper; are you sure you're using it for its intended purpose? - Clint
@Clint it is not lazy neither abuse. There are plenty of properties. Also the collection type part in the destination functionally read-only, so no need to deep copy. - g.pickardou
@tdbeckett I believe you are confused. He wants to deep copy the root object but shallow copy the properties/references. - nightski
@tdbeckett: Shallow copy is not the reference copy. Btw reference copy is not even a term. It is reference assignment. Please google for shallow copy it will turn out what it is. - g.pickardou

1 Answers

0
votes

It's weird that AutoMapper documentation has no mention of this behavior. AutoMapper tries to deep clone the custom collection into a List<>.

interface IMyCollection : IEnumerable<int> // or class
{
}

class From
{
    public IMyCollection Collection { get; set; }
}

class To
{
    public IMyCollection Collection { get; set; }
}

Solution:

cfg.CreateMap<IMyCollection, IMyCollection>().ConvertUsing(s => s); // force shallow clone
cfg.CreateMap<From, To>();