Can I centralize mapping which I want to ignore in AutoMapper?

Viewed 82

I have classes which have the usual CreatedDate, CreatedById, EditedDate, EditedById and etc. fields on which I ignore when mapping from Domain models -> Entity models (they are populated later by the database).

My mappings are now littered with mapping ignore looking a bit like

CreateMap<UpdateProvider, ProviderInstance>()
            .ForMember(e => e.Id, opt => opt.Ignore())
            .ForMember(e => e.CreatedDate, opt => opt.Ignore())
            .ForMember(e => e.CreatedById, opt => opt.Ignore())
            .ForMember(e => e.EditedDate, opt => opt.Ignore())
            .ForMember(e => e.EditedById, opt => opt.Ignore())
            .ForMember(e => e.ArchivedDate, opt => opt.Ignore())
            .ForMember(e => e.ArchivedById, opt => opt.Ignore());

Can I centralize this in a single method to adhere to the DRY principle. If it helps each of these fields have interfaces called IIdentifiable, ICreateable, IEditable, IArchiveable.

I was hoping to just create an extension method of something like .IgnoreDbGeneratedFields<TDestination>()

1 Answers

An extension method along the following lines should work:

    public static IMappingExpression<T1, T2> IgnoreDbGeneratedFields<T1, T2>(this IMappingExpression<T1, T2> e)
    where T2 : IIdentifiable, ICreateable, IEditable, IArchiveable
{
    return e
        .ForMember(x => x.Id, opt => opt.Ignore())
        .ForMember(x => x.CreatedDate, opt => opt.Ignore())
        .ForMember(x => x.CreatedById, opt => opt.Ignore())
        .ForMember(x => x.EditedDate, opt => opt.Ignore())
        .ForMember(x => x.EditedById, opt => opt.Ignore())
        .ForMember(x => x.ArchivedDate, opt => opt.Ignore())
        .ForMember(x => x.ArchivedById, opt => opt.Ignore());
}
Related