I have four tables: Users, Songs, Genres, and FavoriteGenres.
Users are allowed to favorite genres and when they navigate to their dashboard, they are presented with a list of songs that are within any of their favorite genres.
I have the following EF core code which accomplishes this:
dbContext
.Songs
.Include(song => song.Genre)
.Where(song => song.Genre.FavoriteGenres.Any(favoriteGenre => favoriteGenre.UserId == userId))
.OrderBy(song => song.CreatedDateTimeOffset)
.ToListAsync(cancellationToken);
The query that is output (which works fine) is:
SELECT [s].[Id], [s].[Title], [s].[CreatedDateTimeOffset], [g].[Id], [g].[Name]
FROM [Songs] AS [s]
INNER JOIN [Genres] AS [g] ON [s].[GenreId] = [g].[Id]
WHERE EXISTS (
SELECT 1
FROM [FavoriteGenres] AS [f]
WHERE ([g].[Id] = [f].[GenreId]) AND ([f].[UserId] = @__userId_0))
ORDER BY [s].[CreatedDateTimeOffset] DESC
I was just wondering if it is possible to hint at EF core to generate the following query, which I believe may be more optimal (though I would love to be told I am wrong!):
SELECT [s].[Id], [s].[Title], [s].[CreatedDateTimeOffset], [g].[Id], [g].[Name]
FROM [Songs] AS [s]
INNER JOIN [Genres] AS [g] ON [s].[GenreId] = [g].[Id]
INNER JOIN [FavoriteGenres] AS [f] ON [f].[GenreId] = [g].[Id]
WHERE [f].[UserId] = @__userId_0
ORDER BY [s].[CreatedDateTimeOffset] DESC
The execution plans look very similar, but quite honestly I am not an expert at reading them. Any sort of help would be very appreciated :)