如何使用AutoMapper填充空对象?

时间:2012-07-12 16:10:22

标签: automapper

如果发布评论的人是访客,则CommentUserViewModel为null,这是正确的,因为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>();

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

我认为以下映射会为guest虚拟机填充User对象,但它没有任何影响。客人名称甚至可以为空,因此我也可以使用null替换。

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

1 个答案:

答案 0 :(得分: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)));