简体   繁体   中英

Automapper Inherited Source and Destination

I have inherited my base "User" class to create role specific types.

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.

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.

//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.

Is Automapper just unable to map inherited types like this? Or am I missing something?

You need to create map for base type, and then include inherited type. See automapper docs here .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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