Use Automapper to flatten sub-class of property

Posted by Neil on Stack Overflow See other posts from Stack Overflow or by Neil
Published on 2010-05-17T04:50:04Z Indexed on 2010/05/17 5:00 UTC
Read the original article Hit count: 308

Filed under:
|
|

Given the classes:

public class Person
{
    public string Name { get; set; }
}

public class Student : Person
{
    public int StudentId { get; set; }
}

public class Source
{
    public Person Person { get; set; }
}

public class Dest
{
    public string PersonName { get; set; }
    public int? PersonStudentId { get; set; }
}

I want to use Automapper to map Source -> Dest.

This test obviously fails:

Mapper.CreateMap<Source, Dest>();
var source = new Source() { Person = new Student(){ Name = "J", StudentId = 5 }};

var dest = Mapper.Map<Source, Dest>(source);
Assert.AreEqual(5, dest.PersonStudentId);

What would be the best approach to mapping this given that "Person" is actually a heavily used data-type throughout our domain model.

© Stack Overflow or respective owner

Related posts about automapper

Related posts about subclass