c# - 具有基类和不同实现配置选项的自动映射器

标签 c# .net automapper

我有两个类(MVC View 模型)继承自一个抽象基类。

abstract class BaseModel { }

class Car : BaseModel 
{
    public string Speed { get; set; }
}

class Camper : BaseModel
{
    public int Beds { get; set; } 
}

并希望使用基类配置 AutoMapper,例如:

Mapper.CreateMap<BaseModel, DataDestination>();

var someObj = new DataDastination();
Mapper.Map(instanceOfBaseModel, someObj);

这里我得到错误,因为 Automapper 没有 Car 或 Camper 的配置。尝试用这样的东西配置 Automapper:

Mapper.CreateMap<BaseModel, DataDestination>()
    .ForMember(dest => dest.SomeProp, mapper => mapper.MapFrom( .... ));

在 MapFrom 中,我只能看到基类的属性!如何配置 Automapper 以使用 BaseClass,以及 Car 和 Camper 的特定 ForMember 表达式?例如,如果是 Car,则从 this 映射此属性,如果是 Camper,则从其他地方映射此属性。

最佳答案

这里是描述Mapping Inheritance的主题.

以下应该适合您:

Mapper.CreateMap<BaseModel, DataDastination>()
    .Include<Car, DataDastination>()
    .Include<Camper, DataDastination>();//.ForMember(general mapping)
Mapper.CreateMap<Car, DataDastination>();//.ForMember(some specific mapping)
Mapper.CreateMap<Camper, DataDastination>();//.ForMember(some specific mapping)

关于c# - 具有基类和不同实现配置选项的自动映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11264455/

相关文章:

c# - Application.Current.Shutdown() 没有杀死我的应用程序

c# - ProtoInclude 属性是什么意思(在 protobuf-net 中)

c# - 使用 C# 在 Windows Server 2003 上查询 EventLog

.net - FxCop 10.0 独立无法分析使用 AutoMapper 的程序集

c# - 使用自动映射器对对象层次结构进行非规范化

c# - 使用 Html.Helper 函数创建多行文本框

c# - 如何将 ObservableCollections 绑定(bind)到 ItemsSource?

c# - 我如何对这个(正确地)抛出异常的异步方法进行单元测试?

c# - 使用 Automapper 映射具有相似名称的成员

javascript - 如何处理 JavaScript 弹出的警报? Selenium 网络驱动程序