我有两个实体,它们的关系是多对多的。代码如下:
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 关系,我该怎么办?
我对自动映射器很陌生,这是我的第一个问题,我希望我做对了,我非常感谢你的回答和指导如何提问。