【问题标题】:AutoMapper - Ignore properties from base class for all implementationsAutoMapper - 忽略所有实现的基类中的属性
【发布时间】:2013-09-14 00:35:15
【问题描述】:

我想使用 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());

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

【问题讨论】:

  • 想知道使用对象作为源和实体作为目标是否可以工作......Mapper.CreateMap&lt;object, Entity&gt;().ForMember(dest=&gt;dest.CreatedOn, opt=&gt;opt.Ignore()); 猜不透。

标签: c# automapper


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    如果您只想忽略实体上的映射,但将它们放在 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;
    }
    

    【讨论】:

      【解决方案3】:
      Mapper.CreateMap<SourceType, DestinationType>().ForAllMembers(opt => opt.Ignore());
      Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*map manual*/);
      Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*map manual*/);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        相关资源
        最近更新 更多