简体   繁体   中英

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.

eg

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM