Faust
Faust

Reputation: 15404

Automapper with Entity Framework inheritance

I suspect there is some simple configuration with AutoMapper to get the mapping I want, but I have no clue. Can anyone point me in the right direction?

Here is my situation:

I've defined table-per-type inheritance in Entity Framework with a supertype of Publication and a sub-type of Article (+ 5 other sub-types)

ArticleAdmin is my (MVC) viewmodel, which inherits from a PublicationAdmin viewmodel.

Mapping the viewmodel to the domain sub-type works fine:

Mapper.CreateMap<ArticleAdmin, Article>();
var _Article = Mapper.Map<ArticleAdmin, Article>(article);;

And so I have no problems adding articles.

But going the other way doesn't seem quite so easy. This won't populate the sub-type fields:

Mapper.CreateMap<Article, ArticleAdmin>();
var _Article = Mapper.Map<Article, ArticleAdmin>(_article_entity);

UPDATE

I've revised this, as part of the problem was that my generic repository was returning an entity of the super-type, instead of the sub-type . Now the domain-to-viewmodel mapping compiles, but it still maps nulls to the sub-type fields, while correctly mapping the super-type fields.

Upvotes: 1

Views: 977

Answers (1)

GlennMoseley
GlennMoseley

Reputation: 153

Afraid I don't have enough rep for comments to query what you have entered, so forgive me if this is way off the mark.

Do the classes you are trying to map follow the same specification?

If not then you may need to do some configuration in your CreateMap. You can use ForMember to configure the source and destination of each property.

Mapper.CreateMap<Article, ArticleAdmin>()
.ForMember(dest => dest.DestProperty, opt => opt.MapFrom(src => src.SourceProperty))

If this isnt it then maybe you could post the specification of the class you are looking to post from>to.

Upvotes: 1

Related Questions