1

我有两个实体,它们的关系是多对多的。代码如下:

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 创建一个实体并将它们添加到 DbContext 中,即 post、tag(如果不存在)和 postTag 关系,我该怎么办?

我对自动映射器很陌生,这是我的第一个问题,我希望我做对了,我非常感谢你的回答和指导如何提问。

4

1 回答 1

-1

我认为你有两个选择。

1)反向映射

您可以添加.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();

PostViewModel2)您可以为to定义一个新配置Post

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

然后Mapper.Map<Post>(postViewModel)

于 2019-01-02T14:14:30.500 回答