C# 无法在运行时使用多个包含过滤查询以获取异常

C# 无法在运行时使用多个包含过滤查询以获取异常,c#,entity-framework,linq,entity-framework-6,C#,Entity Framework,Linq,Entity Framework 6,这就是我的疑问: var units = _context.Units.Include(m => m.Modules.Select(t => t.Tests.Select(q => q.Questions))) .ToList(); 当我在t.Tests集合的末尾添加.Where()时,我在运行时会遇到以下异常: System.ArgumentException:'包含路径表达式必须引用 在类型上定

这就是我的疑问:

   var units = _context.Units.Include(m =>
                    m.Modules.Select(t => t.Tests.Select(q => q.Questions)))
                .ToList();
当我在
t.Tests
集合的末尾添加
.Where()
时,我在运行时会遇到以下异常:

System.ArgumentException:'包含路径表达式必须引用 在类型上定义的导航属性。使用虚线路径 引用导航属性和集合的选择运算符 导航属性。 参数名称:路径'

如何过滤
t.Tests
集合而不获得错误

只需知道我想在客户端加载所有单元/模块/Tests.filter/Questions.filter

我的模型:

EF模型:

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;}
}
类单位
{
公共int Id{get;set;}
公共ICollection模块{get;set;}
}
类模块
{
公共int Id{get;set;}
公共ICollection测试{get;set;}
}
课堂测试
{
公共int Id{get;set;}
公共ICollection问题{get;set;}
公共bool IsActive{get;set;}
}
课堂提问
{
公共int Id{get;set;}
公共ICollection测试{get;set;}
公共bool IsActive{get;set;}
}
为什么这不是复制品


这不仅是一个1到N的筛选问题,而且是一个N到M关系的筛选问题,这在已经解决的解决方案中显示的linq查询样式中是不容易做到的。

Include
在要筛选子项的情况下不起作用。改用匿名类:

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

现在,您可以迭代
unitsWithQuestions
,并通过引用匿名类的
Unit
TestQuestions
成员来检索相关部分。

您的模型看起来怎么样?@Nashmár发布了我的模型@ThomasAyoub关于使用.Where()在多对多上包含,请参阅测试/问题。我猜使用iterate时,您的意思是在客户端上执行过滤,就像您已经执行的那样。ToList()!对吗?好的,我可以在匿名类中过滤它。我不得不使用SelectMany作为模块。SelectMany和我的值现在有点不同了。但是嘿,你给了我一个很好的暗示!非常感谢!