【发布时间】:2020-10-12 10:10:27
【问题描述】:
我是 Automapper 的新手,我在映射具有多对多关系的类时遇到问题。 我想我需要像嵌套映射这样的东西,但文档对我来说似乎并不清晰。我知道我在 AutoMapper 配置方面做错了,但我不知道出了什么问题。
当我将一本新书添加到数据库中时,我希望收到有关该书以及该书作者的信息。 (预期的 JSON 结果如下)
我有以下课程:
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string ISBN { get; set; }
public string Category { get; set; }
public int PublisherId { get; set; }
public Publisher Publisher { get; set; }
public ICollection<BookAuthor> BooksAuthors { get; set; }
}
public class Author
{
public int AuthorId { get; set; }
public string AuthorName { get; set; }
public string AuthorLastName { get; set; }
public ICollection<BookAuthor> BooksAuthors { get; set; }
}
public class BookAuthor
{
public int BookId { get; set; }
public Book Book { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
DTO
public class BookForNewDto
{
public string Title { get; set; }
public string ISBN { get; set; }
public string Category { get; set; }
public int PublisherId { get; set; }
public ICollection<AuthorForNewBookDto> Authors { get; set; }
}
public class AuthorForNewBookDto
{
public int AuthorId { get; set; }
}
BookController (AddBook)
public async Task<IActionResult> AddBook([FromBody] BookForNewDto bookForNewDto)
{
var bookToCreate = _mapper.Map<Book>(bookForNewDto);
var bookToReturn = _mapper.Map<BookForNewDto>(bookToCreate);
var bookToAdd = await _context.Books.AddAsync(bookToCreate);
await _context.SaveChangesAsync();
var bookIdToAdd = bookToCreate.BookId;
var authorIdToAdd = bookForNewDto.Authors.Select(aa => aa.AuthorId).ToList();
foreach (var item in authorIdToAdd)
{
var bookAuthorToAdd = new BookAuthor()
{
BookId = bookIdToAdd,
AuthorId = item
};
var newBookAuthor = await _context.BooksAuthors.AddAsync(bookAuthorToAdd);
await _context.SaveChangesAsync();
}
return Ok(bookToReturn);
}
AutoMapper Profiler // 我只附上了与添加新书有关的部分。
public class AutoMapping : Profile
{
public AutoMapping()
{
CreateMap<BookForNewDto, Book>();
CreateMap<Book, BookForNewDto>()
.ForMember(dto => dto.PublisherId, opt => opt.MapFrom(x => x.PublisherId))
.ForMember(dto => dto.Authors, c => c.MapFrom(c => c.BooksAuthors));
CreateMap<BookForNewDto, AuthorForNewBookDto>()
.ForMember(dto => dto.AuthorId, opt => opt.MapFrom(x => x.Authors.Select(aaa => aaa.AuthorId)));
}
我的问题是如何配置我的 AutoMapper Profiler 以获得下面的 JSON 结果?我对作者有意见。我仍然得到一个空列表。
{
"title": "sample title",
"isbn": "123-41-5-12311",
"category": "test",
"publisherId": 1,
"authors": [
{
"authorId": 43
},
{
"authorId": 45
},
{
"authorId": 134
},
}
【问题讨论】:
标签: c# .net-core many-to-many automapper automapping