1

Thats my query:

   var units = _context.Units.Include(m =>
                    m.Modules.Select(t => t.Tests.Select(q => q.Questions)))
                .ToList();

When I add .Where() at the end of the t.Tests collection I get this exception at runtime:

System.ArgumentException: 'The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path'

How can I though filter the t.Tests collection without getting the error?

Just know I want all the Units/Module/Tests.filter/Questions.filter loaded on the client.

My Model:

EF Model:

class Unit
{
    public int Id { get; set; }
    public ICollection<Module> Modules { get; set; }
}

class Module
{
    public int Id { get; set; }
    public ICollection<Test> Tests { get; set; }
}

class Test
{
    public int Id { get; set; }
    public ICollection<Question> Questions { get; set; }
    public bool IsActive { get; set;}
}

class Question
{
    public int Id { get; set; }
    public ICollection<Test> Tests { get; set; }
    public bool IsActive { get; set;}
}

Why this is not a duplicate!

Its a filter problem not only with 1 to N but also N to M relation which can not be easily done with the linq query style shown in the already solved solution.

HelloWorld
  • 4,671
  • 12
  • 46
  • 78

1 Answers1

1

Include does not work in situations where you would like to filter children. Use an anonymous class instead:

var unitsWithQuestions = _context.Units.Select(m => new {
    Unit = m
,   TestQuestions = m.Modules.Select(t =>
        t.Tests.Select(q => q.Questions)
    ).ToList()
}).ToList();

Now you can iterate unitsWithQuestions, and retrieve the relevant parts by referring to Unit and TestQuestions members of the anonymous class.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I guess with iterate you mean the filtering is executed on the client as you already did .ToList()! Is that correct? – HelloWorld May 19 '18 at 15:38
  • ok I could filter it inside the anonymous class. I had to use SelectMany for the Modules.Select and my values are a bit different now. But hey you gave that great hint! Much appreciate it! – HelloWorld May 19 '18 at 16:22