Jürgen Steinblock Jürgen Steinblock - 1 year ago 112
C# Question

AutoMapper - Ignore properties from base class for all implementations

I want to use AutoMapper to import data.

My destination classes all inherit from a base class

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 ...

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download