使用自动映射以多对多关系将ViewModel映射到实体

时间:2018-12-26 14:49:38

标签: entity-framework-core automapper

我有两个实体,它们之间的关系很多。代码如下:

public class Post : Entity
{
    //public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public DateTime CreateTime { get; set; }
    public DateTime LastModify { get; set; }

    public ICollection<PostTag> PostTags { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}
public class Tag :Entity
{
    //public int Id { get; set; }
    public string TagName { get; set; }

    public ICollection<PostTag> PostTags { get; set; }
}
public class PostTag :Entity
{
    //public int Id { get; set; }

    public int PostId { get; set; }
    public Post Post { get; set; }
    public int TagId { get; set; }
    public Tag Tag { get; set; }
}
public class PostViewModel
{
    public string Title { get; set; }
    public string Body { get; set; }
    public DateTime CreateTime { get; set; }
    public DateTime LastModify { get; set; }
    public int AuthorId { get; set; }
    public string AuthorName { get; set; }
    public List<TagViewModel> Tags { get; set; }
}

现在,我已经创建了从实体到视图模型的映射配置:

CreateMap<Post, PostViewModel>()
    .ForMember(dest => dest.AuthorId, opt => opt.MapFrom(src => src.Author.Id))
    .ForMember(dest => dest.Tags, opt => opt.MapFrom(src => src.PostTags))
    .ForMember(dest => dest.AuthorName, opt => opt.MapFrom(src => src.Author.User.LastName))
    .ForMember(dest => dest.Body, opt => opt.MapFrom(src => src.Body))
    .ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Title))
    .ForMember(dest => dest.CreateTime, opt => opt.MapFrom(src => src.CreateTime))
    .ForMember(dest => dest.LastModify, opt => opt.MapFrom(src => src.LastModify))
    .ForMember(dest => dest.Tags, opt => opt.MapFrom(src => src.PostTags.Select(y => y.Tag).ToList()));

我的问题是,当我收到类似PostViewModel的信息时:

public async Task<IActionResult> Post([FromBody] PostViewModel postViewModel)
{

}

如何将PostViewModel映射到Post?我想从PostViewModel创建一个实体,并将它们(即post,tag(如果不存在)和postTag关系)添加到DbContext中,该怎么办?

对于automapper来说我还很陌生,这是我的第一个问题,希望我做对了,我非常感谢您的回答和如何提出要求的指导。

1 个答案:

答案 0 :(得分:-1)

我认为您有两个选择。

1)Reverse mapping

您只需在映射配置的末尾添加.ReverseMap()

CreateMap<Post, PostViewModel>()
    .ForMember(dest => dest.AuthorId, opt => opt.MapFrom(src => src.Author.Id))
    ...
    .ForMember(dest => dest.Tags, opt => opt.MapFrom(src => src.PostTags.Select(y => y.Tag).ToList()))
    .ReverseMap();

2)您可以为PostViewModelPost定义新的配置

CreateMap<PostViewModel, Post>()
    .ForMember(dest => dest.Author.Id, opt => opt.MapFrom(src => src.AuthorId))
    ...etc

然后Mapper.Map<Post>(postViewModel)