문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top