5

我想使用 AutoMapper 导入数据。

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

假设我有一个源类 Unit:

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

效果很好,问题是我有多个从实体继承的类,我不想重复自己。可以告诉 AutoMapperFor every class that interits from entity ignore the properties ...吗?

4

3 回答 3

4

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

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

Mapper.AddGlobalIgnore("CreatedOn");
Mapper.AddGlobalIgnore("CreatedBy");
Mapper.AddGlobalIgnore("ModifiedOn");
Mapper.AddGlobalIgnore("ModifiedBy");
于 2013-09-12T05:37:38.700 回答
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;
}
于 2016-02-10T17:09:49.473 回答
1
Mapper.CreateMap<SourceType, DestinationType>().ForAllMembers(opt => opt.Ignore());
Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*map manual*/);
Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*map manual*/);
于 2016-09-22T11:29:58.440 回答