spacewalker
spacewalker

Reputation: 21

EF Core exclude certain property in query, many-to-many relationship

How do I query certain properties only in a database that has many-to-many relationship?

So I have a book that can have multiple authors

public class Book
{
    public Book()
    {
        Authors = new List<BookAuthor>();
    }

    public string Id { get; set; }
    public string Description { get; set; }

    public List<BookAuthor> Authors { get; set; }
}

Joined table for Book and Author

public class BookAuthor
{
    public string BookId{ get; set; }
    public string AuthorId{ get; set; }

    public Book book{ get; set; }
    public Author author{ get; set; }
}

Finally, the Author can write multiple books

public class Author
{
    public string Id { get; set; }
    public string Name { get; set; }

    public List<BookAuthor> books { get; set; }

}

Now, when I want to query a book and return the book id and description NOT the List of authors of that book

return await _context.Book.Select(x => new Book
        {
            Id = x.Id,
            Description = x.Description,        
        }).ToListAsync();

When I do this I got

{
    "id": "BOOK123",
    "description": "Stack Overflow 101",
    "Authors": []
}

I want to exclude the property Author from Book class in my query's return. How do I achieve this?

Upvotes: 2

Views: 2086

Answers (1)

Nemanja Todorovic
Nemanja Todorovic

Reputation: 2820

You would need to create a DTO object for Book:

public class BookDto
{
   public string Id { get; set; }
   public string Description { get; set; }
}

and then call:

return await _context.Book.Select(x => new BookDto
{
    Id = x.Id,
    Description = x.Description,        
}).ToListAsync();

More advanced approach would be to use Automapper (https://automapper.org/) and create a mapping profile between your Book and BookDto:

public class BookProfile : Profile
    {
        public BookProfile()
        {
            CreateMap<Book, BookDto>();
        }
    }

and then you could retrieve your BookDtos like this:

return await _context.Book
.ProjectTo<BookDto>(_mapper.ConfigurationProvider)
.ToListAsync();

where _mapper is of type IMapper.

Upvotes: 1

Related Questions