Faust
Faust

Reputation: 15404

Automapper -- mapping many-to-many lookups from Entity Framework to viewmodel

I believe this is an AutoMapper basics question:

I have an single "article" Entity Framework entity that I am mapping to a viewmodel to pass to a view for edits. This works fine:

Mapper.CreateMap<Article, ArticleAdmin>();
var articleData = Mapper.Map<Article, ArticleAdmin>(articleEntity);

Now, my EF model includes many-to-many relation to a Topics table via a TopicArticles lookup table, and I want to manage associations when I'm editting the article data.

So I add this to my viewmodel:

public ICollection<TopicArticle> TopicArticles { get; set; } 

I believe this is correct specification to mirror the entity type -- my EF model has the TopicArticles association member as an EntityCollection.

and I add a second viewmodel class to populate the list:

public class TopicArticle
{
    public int ArticleId { get; set; }
    public int TopicId { get; set; }
    public bool IsPrimaryTopic { get; set; }
}

When I run the mapping, I get "Missing type map configuration or unsupported mapping." Which is understandable as I've not told Automapper about my TopicArticle viewmodel class.

So: QUESTION:

How do I change my mapping to account for this extra layer?

(I don't really understand the Automapper syntax for how this should be mapped.)

Also: have I missed anything else?

NOTE / UPDATE:

There were some errors in my posted code, any "publication" that appeared was incorrect, and should have been "article" -- that was because I'm simplifying the situration a bit: articles actually inhereit from publications, but I did not want that complexity in this Question.

Upvotes: 1

Views: 1997

Answers (1)

Faust
Faust

Reputation: 15404

OK, this really is basic. My problem was not getting to the actual Automapper documentation. Googling "automapper documentation" gets this link as the top response:

http://automapper.codeplex.com/documentation

which is a useless TOC.

The real documentation is accessed from the home page.

The answer to my question is simple: First, I change the name of my second viewmodel class for clarity:

public class TopicArticleAdmin

Then back in my action, I add one more mapping line:

Mapper.CreateMap<Publication, ArticleAdmin>();
Mapper.CreateMap<TopicPublication, TopicPublicationAdmin>();
var articles = Mapper.Map<IEnumerable<Publication>, IEnumerable<ArticleAdmin>>(
    articleEntities
);

Upvotes: 2

Related Questions