Reputation: 45
Refer the following code
public class Author
{
public string Name { get; set; }
public ICollection<Book> Books { get; set;}
}
public class Book
{
public string Name { get; set; }
public int AuthorId { get; set; }
public virtual Author Author { get; set; }
}
[HttpGet]
public async Task<IActionResult> GetAuthors([FromQuery] GridifyQuery query)
{
var authors = DbContext.Authors
.AsNoTracking()
.ApplyFiltering(query);
var authorsDto = await ObjectMapper.ProjectTo<AuthorDto>(authors)
.ToListAsync();
return Ok(authorsDto);
}
Problem
I want to directly fetch list of authors from Authors
table by applying filter on property Author.Books
, which is not possible at the moment (i.e. filtering on ICollection<T>
).
I am aware of the workaround where I can fetch the list of Authors by querying the Books
table and then navigating back to Authors
. However, I would like to avoid this approach and query the Authors
table directly.
I tried making Custom filters, but I am having difficulty integrating LINQ queries into the filtering logic.
References
Upvotes: 0
Views: 236
Reputation: 36715
A simple working demo you could follow:
[HttpGet]
public async Task<IActionResult> GetAuthors([FromQuery] GridifyQuery query)
{
//query for example: "BookName=book1"
var mapping = new GridifyMapper<Author>()
.AddMap("BookName", x => x.Books.Select(c => c.Name));
var authors = _context.Author
.AsNoTracking()
.Include(a => a.Books)
.ApplyFiltering(query, mapping).ToList();
//do your stuff...
return Ok(authors);
}
The request url should be:https://localhost:portNumber/home/getauthors?filter=BookName=book1
, book1
is the name of the Book.
Upvotes: 1