Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper - Ignore properties from base class for all implementations

Tags:

c#

automapper

I want to use AutoMapper to import data.

My destination classes all inherit from a base class Entity which has some properties defined that does not exist in the source (CreatedOn, CreatedBy, ModifiedOn, ModifiedBy)

Let's say I have a source class Unit:

public class UnitOld
{
    public int Id { get; set; }
    public string Name { get; set; }
}

this is my destination class Unit:

public class Unit : Entity
{
    public Guid UnitId { get; set; }
    public string UnitName { get; set; }
}

public class Entity
{
    public string CreatedOn { get; set; }
    public string CreatedBy { get; set; }
    public string ModifiedOn { get; set; }
    public string ModifiedBy { get; set; }
}

Now to create my mapping I have to write:

        Mapper.CreateMap<UnitOld, Unit>()
            .ForMember(d => d.UnitName, o => o.MapFrom(s => s.Name))
            .ForMember(d => d.UnitId , o => o.Ignore())
            .ForMember(d => d.CreatedOn, o => o.Ignore())
            .ForMember(d => d.CreatedBy, o => o.Ignore())
            .ForMember(d => d.ModifiedOn, o => o.Ignore())
            .ForMember(d => d.ModifiedBy, o => o.Ignore());

which works fine, the thing is I have multiple classes that inherit from entity and I don't want to repeat myself. Is it possible to tell AutoMapper For every class that interits from entity ignore the properties ...?

like image 981
Jürgen Steinblock Avatar asked Sep 10 '13 10:09

Jürgen Steinblock


1 Answers

I suppose there could be a better solution, that will tell automapper to ignore some base class properties in every mapping.

However, this method works for me (this will ignore all properties starting with these strings in all mappings.

Mapper.AddGlobalIgnore("CreatedOn");
Mapper.AddGlobalIgnore("CreatedBy");
Mapper.AddGlobalIgnore("ModifiedOn");
Mapper.AddGlobalIgnore("ModifiedBy");
like image 156
Jürgen Steinblock Avatar answered Sep 24 '22 20:09

Jürgen Steinblock