0

I have fairly simple question regarding Automapper mapping definition. My intent is to deep clone an object via Automapper while ignoring 'Id' property, this is why i have chosen it to customize the mapping.

public interface IEntity<T>
{
    T Id { get; }
}

public abstract class Entity : IEntity<Guid>
{
    public Guid Id { get; set; }
}

All my entities are deriving from Entity class and i simply wants to ignore all Id property in the nested hierarchy of my object without being so explicit about the mapping definition.

So far i have come up with the following piece of code to do the cloning but how to ignore Id property mapping for the nested properties and not just for the root.

public static T AutomapperClone<T>(this T source)
    where T : IEntity<Guid>
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<T, T>()
            .ForMember(d => d.Id, o => o.Ignore());
    });
    // checking configuration validity
    config.AssertConfigurationIsValid();
    // creating mapper
    var mapper = config.CreateMapper();
    var copy = mapper.Map<T, T>(source);
    return copy;
}

The idea is that all entities get their new Id instead of using the same mapped ones. Is it accomplishable via Automapper?

Appreciate your feedback.

Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
  • AM is mainly a cache and that cache lives in MapperConfiguration. You app should have only one such object. So unless you're willing to spend some time understanding how AM works, you're better off mapping by hand. – Lucian Bargaoanu Nov 24 '18 at 08:47
  • Appreciate your comment, yes i have basic understanding of AM but the issue is that there are few dynamic modules which are loaded on demand and extends the model so i can't define the one time MapperConfiguration fully comprising of extended models. So i am trying to seek some help on AM if my source and target Models are same. Its a valid use case and i am asking this question if accomplishable via AM – Furqan Safdar Nov 24 '18 at 09:15
  • No, modules shouldn't use the MappingConfiguration, they should define profiles to be loaded by the MappingConfiguration singleton defined by the app. So you should fix the way you use AM, before trying to make your mappings work. When your house is on fire, you don't try to fix the faucets. – Lucian Bargaoanu Nov 24 '18 at 09:28

1 Answers1

0

I wouldn't use Automapper for this person, try AnyClone to do this. It does deep cloning and can ignore by property name which seems to be what you are looking for.

Michael Brown
  • 1,585
  • 1
  • 22
  • 36