Entity Framework, Polymorphism, and AutoMapper: Can't We All Be Friends?

Published on Friday, April 22, 2011

At work we were running into an interesting issue. We are using EF Code First, AutoMapper, and the dynamic proxies generated by EF. We map our domain entities onto our view models.

The Problem

AutoMapper fails to map a derived type to a view model base class for use in a general-use scenario:

public IEnumerable<AbstractViewModel> GetPolymorphicClasses() {
    var list = db.AbstractClasses.ToList();

    // list is a list of dynamically proxied derived types
    // DerivedTypeA, DerivedTypeB, and so on
    // aka DynamicProxy_xxxxxxx
    return Mapper.Map<IEnumerable<AbstractClass>, IEnumerable<AbstractViewModel>>(list);

The "Solution"

This is not a solution, but it's the best I could do with limited knowledge of AutoMapper and a need to just get it working quickly. Thanks to this post on the same problem, I was able to retrofit the answerer's answer to a solution that worked for me (his generated a stack overflow because it seemed to get stuck converting in an infinite loop).

If Jimmy Bogard reads this, please tell me what I'm doing wrong and how to actually fix it:

About Kamran
I'm a technologist, speaker, and Pluralsight author and I specialize in building full-stack solutions with a focus on modern web technology and cloud native architecture.
comments powered by Disqus
comments powered by Disqus