2

如果发表评论的人是客人,那么 CommentUserViewModel 为空,这是正确的,因为 UserName 是从 User 表中填充的,但是如何填充 CommentUserViewModel 来宾姓名存储在 Comment 表中?

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

我的映射是:

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

如果没有来宾帖子,这将起作用(因为在检查用户属性时我没有遇到空异常)。

我认为下面的映射会为客人填充用户对象,但它没有影响。客人姓名甚至可以是空白的,所以我也有一个空替代品。

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

如何更正映射以填充 User.GuestName?

编辑

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

我正在使用实体框架:

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

1 回答 1

0

这篇文章有帮助: 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)));
于 2012-07-16T11:06:28.563 回答