Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include / ThenInclude with where in EF Core

I need to use where in ThenInclude

        var templatesFields = await _context.Sections
        .Include(x => x.Subtitles)
        .ThenInclude(r => r.Fields.Where(t=>t.TemplatesFields.TemplateID==TemplateID))
        .ThenInclude(r => r.OptionSources)
        .ThenInclude(r => r.OptionsSourcesDetails)
        .ToListAsync();
like image 637
Rayan Avatar asked Feb 10 '19 19:02

Rayan


People also ask

What is include and ThenInclude in Entity Framework?

Entity Framework Classic ThenIncludeThe ThenInclude method moves the chaining level to the property included. It allows us to include related objects from the next level. ThenInclude is a syntactic sugar method to make it easier and clearer to include multiple related objects.

HOW include works Entity Framework Core?

Entity Framework Core supports eager loading of related entities, same as EF 6, using the Include() extension method and projection query. In addition to this, it also provides the ThenInclude() extension method to load multiple levels of related entities. (EF 6 does not support the ThenInclude() method.)

How do I load related entities in Entity Framework Core?

Entity Framework Core allows you to use the navigation properties in your model to load related entities. There are three common O/RM patterns used to load related data. Eager loading means that the related data is loaded from the database as part of the initial query.


1 Answers

you cannot use where condition inside Include or ThenInclude. What you can do is:

var templatesFields = await _context.Sections
    .Include(x => x.Subtitles)
    .ThenInclude(r => r.Fields)
    .ThenInclude(r => r.OptionSources)
    .ThenInclude(r => r.OptionsSourcesDetails)
    .Where(t=>t.Subtitles.Fields.Any(x => x.TemplatesFields.TemplateID==TemplateID))
    .ToListAsync();

EDIT: This will be possible with .Net Core 5.0 (which is in preview right now)

var blogs = context.Blogs
    .Include(e => e.Posts.Where(p => p.Title.Contains("Cheese")))
    .ToList();

Filtered Include

like image 79
Derviş Kayımbaşıoğlu Avatar answered Oct 02 '22 12:10

Derviş Kayımbaşıoğlu