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

标签 c# automapper

我想用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 对于从实体中插入的每个类忽略属性......

最佳答案

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

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

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

关于c# - AutoMapper - 忽略所有实现的基类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18716570/

相关文章:

c# - .net 中的对象复制方法 : Auto Mapper, Emit Mapper、隐式操作、属性复制

c# - WPF 中的 RichTextBox 没有 .Lines 属性?

c# - 在不使用逗号字符的情况下在 CSV 中显示逗号

c# - Global.asax 中的多个 AutoMapper.Configure()

c# - 如何在 .Net Core 的 Web Api 中使用 AutoMapper?

c# - Automapper 条件语言映射

c# - 我需要帮助弄清楚这种FFT方法

c# - 如何在 ASP.NET Core 2.0 中为 IHttpcontextAccessor 使用依赖注入(inject)

c# - 使用 MvvmCross 从 Xamarin Android 中的 MvxListView 中删除项目

c# - 我可以使用 AutoMapper 映射目标继承而不需要源继承吗?