EFCore does not support many-to-many relationships without creating a linking entity. I need to efficiently select a subset of properties from the 'other end' of the one-to-many-to-one relationship.
I'd swear this would have an answer already but haven't found it.
With these Models:
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string ExtraProperties {get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
public class BookCategory
{
public int BookId { get; set; }
public Book Book { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
This question is an extension of a similar, but different question titled, "Select specific properties from include ones in entity framework core"
I am looking for a query that returns a List<string> categoryNames
of the Categories of the Book.
This nested select, using "projection" results in multiple SQL Queries:
var result= await _ctx.Books
.Where(x => x.BookId == id)
.Select(x => x.BookCategorys
.Select(y => y.Category.CategoryName )
.ToList())
.FirstOrDefaultAsync();
Any solution with .Include(x => x.BookCategory).ThenInclude(x => Category)
will load all the data form the Server before applying the select.
Is there any query that meets the following criteria?:
- Only generates 1 SQL query
- Does not load the entire linking entity and or the entire navigation property 2 'hops' in.
- Returns only
List<string>
of CategoryNames.
I infer from this Entity Framework Core generates two select queries for one-to-many relationship, it's not possible.