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