2

If the person who posted a comment is a guest then CommentUserViewModel is null which is correct because UserName is populated from the User table but how do I populate CommentUserViewModel where the guest name is stored in the Comment table?

public class CommentViewModel
{
  public int Id { get; set; }
  public CommentUserViewModel User { get; set; }
}

public class CommentUserViewModel
{
    public string UserName { get; set; }
    public string GuestName { get; set; }
}

My mappings are:

Mapper.CreateMap<Comment, CommentViewModel>();
Mapper.CreateMap<User, CommentUserViewModel>();

This works if there are no guest posts (as I don't hit a null exception when checking properties on User).

I thought the following mapping would populate the User object for guests but it has no affect. The guest name can even be blank so I have a null substitute on that too.

Mapper.CreateMap<Comment, CommentUserViewModel>()
.ForMember(c => c.GuestName, m => m.MapFrom(s => s.GuestName))
.ForMember(c => c.UserName, m => m.NullSubstitute("Guest"));

How do I correct the mapping to populate User.GuestName?

Edit

var comments = _repository.GetComment();
return Mapper.Map<IEnumerable<Comment>, IEnumerable<CommentViewModel>>(comments);

And I'm using Entity Framework:

public partial class Comment
{
    public int Id { get; set; }
    public string GuestName { get; set; }

    public virtual User User { get; set; }
}

public partial class User
{
    public string UserName { get; set; }
}
KevinUK
  • 5,053
  • 5
  • 33
  • 49
  • So you want to map a `Comment` -> `CommentUserViewModel`, are you explicity calling Map() between the above two types or are you implicity calling Map() on the `Comment` -> `CommentViewModel` and expecting it to know about mapping to the CommentUserViewModel property? Can you post your code? I think I know where you are going wrong but I can't be sure – Charleh Jul 12 '12 at 16:28
  • Please post the relevant code from your `Comment` and `User` entity classes along with these viewmodels. – danludwig Jul 12 '12 at 18:42

1 Answers1

0

This post helped: AutoMapper Map Child Property that also has a map defined

Mapper.CreateMap<Comment, CommentUserViewModel>()
            .ForMember(c => c.UserName, m => m.MapFrom(s => s.User.UserName));

Mapper.CreateMap<Comment, CommentViewModel>()
            .ForMember(c => c.User,
            opt => opt.MapFrom(s => Mapper.Map<Comment, CommentUserViewModel>(s)));
Community
  • 1
  • 1
KevinUK
  • 5,053
  • 5
  • 33
  • 49