0

The majority of my view models inherit from a base view model called EncryptedBaseViewModel. This method encrypts the ID so the user does not see database sensitive information.

I would like to create an AutoMapper mapping that handles all mappings between any entity that maps to the EncryptedBaseViewModel. Get the source ID value and pass it to the destinations SetId method.


The ViewModel Class

class EncryptedBaseViewModel
{
    private string _encryptedId;
    public int Id {get; set; }  // to be after new mapping method is developed.

    public void SetId(int id)
    {
        _encryptedId = Encrypted(id); 
    }

    public string GetId()
    {
        return _encryptedId; 
    }
}

Auto Mapper Example

I have forged hacked this example, which passes the value after mapping as not sure of the approach. Suggestions welcome here.

CreateMap<AnySource, EncryptedBaseViewModel>().ForMember(vm => nameof(vm.Id), opt => opt.Ignore()).AfterMap((src,dest) => dest.SetId(src.Id));

The Questions

  1. Is it possible to make a generic mapper. If so, what do I put in where AnySource is specified?
  2. Will the mapping run as well as any other specific mappings? - I want it to.

I'm trying to avoid having to write the same mapping for every entity, as this could lead to situations where one forgets to do it.

  • 2
    You're better off making the classes you want to map to the destination implement a specific interface and map that instead. – DavidG Aug 15 '17 at 08:34

1 Answers1

1

As @DavidG said, you need a base class or interface for your source. You can also map from object, but that is not terribly useful, because you still need to access the source id somehow. And why the AfterMap? That's a hack. You can write a resolver inline or a resolver class. And about your second point, you need Include if you want both mappings to run (base and derived). The docs.

Lucian Bargaoanu
  • 3,336
  • 3
  • 14
  • 19