Suppose you have a fully defined relationship of books and authors in a large database with many other relationships
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
...
Public int AuthorId { get; set; }
Public Author Author { get; set; }
}
public class Author
{
public int Id { get; set; }
public int GroupId { get; set; }
public string Name { get; set; }
...
public List<Book> Books { get; set; }
...
}
And in your controller you want to return a list of authors, each containing the list of books associated with them using DTOs.
public class BookDTO
{
public int Id { get; set; }
public string Title { get; set; }
}
public class AuthorDTO
{
public int Id { get; set; }
public string Name { get; set; }
public List<BookDTO> Books { get; set; }
}
What is the right way to generate that list of DTOs within a DTO?
Could you do something like this?
var author = from a in _context.authors.Where(a => a.groupId == someGroup)
select new AuthorDTO()
{
Id = a.Id,
Name = a.Name,
Books = (from b in a.Books
select new BookDTO()
{
Id = b.Id,
Title = b.Title
}).ToList()
};
Or maybe something like this?
var author = from a in _context.authors.Where(a => a.groupId == someGroup)
select new AuthorDTO()
{
Id = a.Id,
Name = a.Name,
Books = (from b in _context.books.Where(b => b.AuthorId == a.AuthorId)
select new BookDTO()
{
Id = b.Id,
Title = b.Title
}).ToList()
};
EDIT:
To hopefully be a bit clearer, I rephrased and reposed my question here:
This is Mapper profile example. Profile class comes from Automapper lib.
public class ApplicationServiceAutoMapperProfile : Profile
{
public ApplicationServiceAutoMapperProfile()
{
//Don't use ForMember method if you want to show Id's
CreateMap<Book, BookDTO>()
.ForMember(m => m.Id, opt => opt.Ignore());
CreateMap<Author, AuthorDTO>()
.ForMember(m => m.Id, opt => opt.Ignore());
}
}
This is How you can map.GetAuthors Method returns mapped Dtos.
public class CustomService {
private readonly IMapper _mapper;
private readonly DBContext _context;
public CustomService(IMapper mapper, DBContext context){
_mapper = mapper;
_context = context;
}
public IEnumerable<AuthorDTO> GetAuthors(){
//Automapper automaticaly maps authors's bookdto's also.
var authors = _context.authors.Where(a => a.groupId == 2).ToList();
return _mapper.Map<List<AuthorDTO>>(authors);
}
}