Anthony Walters
Anthony Walters

Reputation: 143

Auto mapper mapping of nested object within a collection

I have a class(Question) which contains a nested propertry called "PostedBy" which is a class called "User" and I am trying to map a datareader to IEnumerable using auto mapper and also want to populate the nested User class of each Question.

e.g.

public class Question
{
   public int  ID{ get;set; }
   public User PostedBy { get; set; }
}

public class User
{
     public string Firstname { get;set; }
     public string Lastname { get;set; }
}

I am using the following code which maps the contents of class Question ok but each nested property PostedBy ( "user" class) is always null and never gets mapped.

           Mapper.CreateMap<IDataReader, Question>().ForMember(destination => destination.PostedBy,
                              options => options.MapFrom(source => Mapper.Map<IDataReader, User>(reader)));

        //now the question information
        Mapper.CreateMap<IDataReader, IEnumerable<Question>>();
        Mapper.AssertConfigurationIsValid();

        IEnumerable<Question> returnValue = Mapper.Map<IDataReader, IEnumerable<Question>>(reader);

Upvotes: 1

Views: 4234

Answers (1)

Anthony Walters
Anthony Walters

Reputation: 143

I've solved the problem. Here's how:

        Mapper.CreateMap<IDataReader, Question>()
            .ForMember(question => question.PostedBy,
                       o =>
                       o.MapFrom(
                           reader =>
                           new User
                               {
                                   Username = reader["Firstname"].ToString(),
                                   EmailAddress = reader["Lastname"].ToString()
                               }));
        Mapper.AssertConfigurationIsValid();

        IEnumerable<Question> mappedQuestions = Mapper.Map<IDataReader, IEnumerable<Question>>(reader);

Upvotes: 2

Related Questions