C# 如何筛选嵌套关系

C# 如何筛选嵌套关系,c#,.net,entity-framework,linq,C#,.net,Entity Framework,Linq,我有三张桌子: public class A { [Key] public int Id {get; set;} public virtual ICollection<B> Bs {get; set;} } public class B { [Key] public int Id {get; set;} public int AId {get; set;} [ForeignKey("AId")] public v

我有三张桌子:

public class A 
{
    [Key]
    public int Id {get; set;}

    public virtual ICollection<B> Bs {get; set;}
}

public class B
{
    [Key]
    public int Id {get; set;}
    public int AId {get; set;}

    [ForeignKey("AId")]
    public virtual A A {get;set;}
    public virtual ICollection<C> Cs {get;set;}
}

public class C
{
    [Key]
    public int Id {get; set;}
    public int BId {get; set;}

    [ForeignKey("BId")]
    public virtual B B {get;set;}
}
公共A类
{
[关键]
公共int Id{get;set;}
公共虚拟ICollection Bs{get;set;}
}
公共B级
{
[关键]
公共int Id{get;set;}
公共int-AId{get;set;}
[外键(“援助”)]
公共虚拟A{get;set;}
公共虚拟ICollection Cs{get;set;}
}
公共C类
{
[关键]
公共int Id{get;set;}
公共整数BId{get;set;}
[外键(“投标”)]
公共虚拟B{get;set;}
}
我想做的是得到一个过滤过的记录列表,它只加载了Bs,然后被过滤,只返回一个同样被过滤过的Cs列表(Cs列表只包含一条记录)。我知道这听起来有点混乱,但也许看看我用代码尝试过的东西会有点道理

以下是我目前的情况:

    int cId = 123;
    var filtered = aRepo.GetAll() // returns dbContext.Set<A>()
        .Where(a => a.Bs
                .Where(b => b.Cs
                    .Where(c => c.Id == cId).FirstOrDefault() != null
                ).FirstOrDefault() != null
        ).ToList();
int-cId=123;
var filtered=aRepo.GetAll()//返回dbContext.Set()
.其中(a=>a.Bs
.其中(b=>b.Cs
.Where(c=>c.Id==cId).FirstOrDefault()!=null
).FirstOrDefault()!=null
).ToList();
这种方法的问题是,一旦我找到了C的匹配项,B就会被加载一个映射到B的所有C的列表,B和a也是如此。我可以理解为什么会发生这种情况,但我似乎不知道如何做到只加载一个C,只有映射到该C的B才会被加载


任何帮助都将不胜感激,谢谢。

尝试使用JOIN获取所有三胞胎:

    var filtered = from a in aRepo.GetAll()
                   join b in bRepo.GetAll() on a.Id equals b.AId
                   join c in cRepo.GetAll() on b.Id equals c.BId 
                   where c.Id == cId
                   select new { aid= a.Id, bid= b.Id,  cid = c.Id};