Search code examples
dapperdapper-extensions

Adding multiple maps when using dapper extensions


I am using dapper extensions and have a question about the class mapper. Unfortunately most of my tables need some mapping done to them such as different schemas etc.

So I find I am typically doing a lot of swapping out the DefaultMapper as per below:

public Hierarchies HierarchyGetByName(string aName)
{
    Hierarchies result;

    using (SqlConnection cn = GetSqlConnection())
    {
        cn.Open();

        Type currModelMapper = DapperExtensions.DapperExtensions.DefaultMapper;
        try
        {
            DapperExtensions.DapperExtensions.DefaultMapper = typeof(HierarchiesMapper);
            IFieldPredicate predicate = Predicates.Field<Hierarchies>(f => f.Name, Operator.Eq, aName);
            result = cn.GetList<Hierarchies>(predicate).FirstOrDefault();
        }
        finally
        {
            DapperExtensions.DapperExtensions.DefaultMapper = currModelMapper;
        }


        cn.Close();
    }

    return result;
}

If I access 2 tables then I have to do this twice for instance.

Is there a way to add all the mapper classes at once to say a collection and depending on the table being accessed the correct one is chosen?


Solution

  • You could add a set of classes within your app that apply custom remapping to your entities. For example these 3 empty classes apply the PrefixDapperTableMapper to the Profile and FileNotificationAdhocRecipient classes while the AnotherDifferentTypeOfDapperClassMapper is applied to NotificationProfile.

    public class ProfileMapper : PrefixDapperTableMapper<Domain.Entities.Profile>
    {
    }
    
    public class FileNotificationAdhocRecipientMapper : PrefixDapperTableMapper<Domain.Entities.FileNotificationAdhocRecipient>
    {
    }
    
    public class NotificationProfileMapper : AnotherDifferentTypeOfDapperClassMapper<Domain.Entities.NotificationProfile>
    {
    }
    

    and your actual mapping code exists in separate mappers (I've not shown AnotherDifferentTypeOfDapperClassMapper but that would be similar to below)

    public class PrefixDapperTableMapper<T> : ClassMapper<T> where T : class
    {
        public PrefixDapperTableMapper()
        {
            AutoMap();
        }
    
        //name or schema manipulations in some overrides here. 
    }
    

    As long as they're in the same assembly, DapperExtensions will find and use them or you can set the mapping assembly with code similar to:

    DapperExtensions.DapperExtensions.SetMappingAssemblies({ typeof(ProfileMapper ).Assembly })