AutoMapper - 忽略所有实现的基类属性

时间:2013-09-10 10:32:11

标签: c# automapper

我想使用AutoMapper导入数据。

我的目标类都继承自基类Entity,其中定义了源中不存在的某些属性(CreatedOn, CreatedBy, ModifiedOn, ModifiedBy

假设我有一个源类单位:

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

这是我的目的地类单位:

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; }
}

现在要创建我的映射,我必须写:

        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());

工作正常,事情是我有多个继承自实体的类,我不想重复自己。是否可以告诉AutoMapper For every class that interits from entity ignore the properties ...

3 个答案:

答案 0 :(得分:4)

我想可以有一个更好的解决方案,它会告诉automapper忽略每个映射中的一些基类属性。

但是,这个方法对我有用(这将忽略所有映射中以这些字符串开头的所有属性。

Mapper.AddGlobalIgnore("CreatedOn");
Mapper.AddGlobalIgnore("CreatedBy");
Mapper.AddGlobalIgnore("ModifiedOn");
Mapper.AddGlobalIgnore("ModifiedBy");

答案 1 :(得分:3)

如果您只想忽略实体上的映射,但是将它们放在Dtos上,那么:

public static IMappingExpression<TSource, TDestination> IgnoreEntityProperties<TSource, TDestination>(this IMappingExpression<TSource, TDestination> mapping)
    where TSource : Entity
    where TDestination : Entity
{
    mapping.ForMember(e => e.Id, c => c.Ignore());
    mapping.ForMember(e => e.CreatedDate, c => c.Ignore());
    mapping.ForMember(e => e.CreatedById, c => c.Ignore());
    mapping.ForMember(e => e.CreatedBy, c => c.Ignore());
    mapping.ForMember(e => e.UpdatedDate, c => c.Ignore());
    mapping.ForMember(e => e.UpdatedById, c => c.Ignore());
    mapping.ForMember(e => e.UpdatedBy, c => c.Ignore());

    return mapping;
}

答案 2 :(得分:0)

Mapper.CreateMap<SourceType, DestinationType>().ForAllMembers(opt => opt.Ignore());
Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*map manual*/);
Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*map manual*/);