Question

I would like to know the best way to query a many to many relationship without first loading all of the relationship objects into memory.

For example, Category and Article have a many to many relationship. This means my Category class has a (lazy-loaded) navigation property as so:

class Category
{
     public long Id {get; set;}
     public ICollection<Articles> Articles {get; set;}
}

If I want to select only the articles that are visible, I can query the navigation property like so:

category.Articles.Where(a => a.IsVisible)

However as far as I am aware, this will load all the related articles into memory before doing the IsVisible check.

Is it possible to query the related articles without loading them into memory, i.e. act on an IQueryable rather than an ICollection? If this were a one to many relationship then I could query the Article DbSet directly to achieve what I am after but the many to many relationship is stored in a link table in sql, meaning I am unable to query this using a DbSet. Is my only option to write the raw sql manually that will query the link table?

Was it helpful?

Solution

Here's one way:

var visibleArticlesQuery = context.Category.Where(c => c.Id == category.Id)
                                           .SelectMany(c => c.Articles)
                                           .Where(a => a.IsVisible);

It's also possible to query the Article DbSet, using Contains, for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top