Danscho Danscho - 1 year ago 187
ASP.NET (C#) Question

AutoMapper map derived type to base type

I am having some issues with AutoMapper and my current implementation of ASP.NET Identity.

My EF code first model resides in its own assembly (compiled with .NET 4.0 because of backwards compatibility with other software).

To use ASP.NET Identity (which needs at least .NET 4.5) I created a separate class in my webapplication which inherits from the database model class and implements

IUser<MyUser, int>

//DB-Assembly: .NET 4.0 Code-First Model
public class ModelUser
//omitted for brevity

//Webapplication: .NET 4.5 -> because I want to use ASP.NET Identity
public class MyUser : ModelUser, IUser<MyUser, int> {}

//ASP.NET Identity UserStore implementation
public class UserStore : IUserStore<MyUser, int>
//Works like a charm
public Task UpdateAsync(MyUser user)
MyUser dbUser = _ctx.Users.Find(user.Id);
ModelUser mappedUser = Mapper.Map(user, dbUser);
_ctx.Users.AddOrUpdate(u => u.Id, mappedUser);
return Task.FromResult(_ctx.SaveChanges());

//Throws "Mapping and metadata information could not be found for EntityType"
public Task CreateAsync(MyUser user)
ModelUser dbUser = new ModelUser();
ModelUser mappedUser = Mapper.Map(user, dbUser); //returns MyUser instead of ModelUser at runtime
return Task.FromResult(_ctx.SaveChanges());

AutoMapper configuration in StartUp.cs:

Mapper.Initialize(cfg => cfg.CreateMap<ModelUser, MyUser>());

The default behavior from AutoMapper is to map to the most specific class.
I want the opposite.

Does anyone know how to tell AutoMapper to map to a specific class or has any other suggestions how I can solve my problem?

Answer Source
AutoMapper.Mapper.CreateMap<ModelUser, MyUser>().ReverseMap(); 

We need to do reversemap to get ModelUser .
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download