简体   繁体   English

Automapper继承的源和目标

[英]Automapper Inherited Source and Destination

I have inherited my base "User" class to create role specific types. 我继承了我的基础“User”类来创建角色特定类型。

eg... 例如...

public class Business : User{
 public string BusinessName;
}

I've done a similar thing for my View Models, starting with a basic "UserModel" and inheriting that to include role specific functionality. 我为我的View Models做了类似的事情,从一个基本的“UserModel”开始,并继承它以包含特定于角色的功能。

public class BusinessModel : UserModel{
 [Required()]
 public string BusinessName;
}

When I use Automapper to map changes to my BusinessModel back to my Business object, it doesn't include any changes to the inherited fields. 当我使用Automapper将更改映射到我的BusinessModel回到我的Business对象时,它不包括对继承字段的任何更改。

//create map between model and business object
Mapper.CreateMap<BusinessModel, Business>();

//load the relevant business
var business = GetCurrentBusiness();

//map the values across
Mapper.Map<BusinessModel, Business>(model, business);

Changes to any fields on the "Business" it's self are present. 对“业务”中的任何字段的更改都存在。 However any changes to fields inherited from User aren't. 但是,从User继承的字段的任何更改都不会。

Is Automapper just unable to map inherited types like this? Automapper是否无法映射这样的继承类型? Or am I missing something? 或者我错过了什么?

You need to create map for base type, and then include inherited type. 您需要为基本类型创建映射,然后包含继承的类型。 See automapper docs here . 在此处查看automapper文档。

Mapper.CreateMap<UserModel, User>()
      .Include<BusinessModel, Business>();
Mapper.CreateMap<BusinessModel, Business>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM