首先在EF代码中嵌套Linq

时间:2012-02-22 16:31:07

标签: c# linq entity-framework

我想知道是否有可能有双巢linq州议员。

我有以下对象(我先使用EF代码)

public class Team
{
    public int TeamId { get; set; }
    public sting Name {get;set;}
    public virtual ICollection<Person> People
}

public class Person
{  
    public int PersonId { get; set; }

    [ForeignKey( "Team" )]
    public int? TeamId { get; set; }
    public Team Team { get; set; }

    public virtual ICollection<Paper> Papers
}

public class Paper
{  
    public int PaperId { get; set; }

    [ForeignKey( "Person" )]
    public int? PersonId { get; set; }
    public Person Person { get; set; }

    public virtual ICollection<Paper> People
}

然后我使用以下linq statemate来创建一个对象

(from t in db.Teams
select new TeamPapers 
{
    TeamName = t.Name
    PaperTotal = t.People.Select(p=>p.Papers).Count()
}).ToList()

但PaperTotal只返回ICollection的数量&lt;纸&gt;不是这些收藏中的论文总数。我想知道是否有人知道如何做到这一点?

2 个答案:

答案 0 :(得分:1)

您是否尝试过SelectMany而不是选择?

(from t in db.Teams
select new TeamPapers 
{
    TeamName = t.Name
    PaperTotal = t.People.**SelectMany**(p=>p.Papers).Count()
}).ToList()

答案 1 :(得分:1)

目前您检索馆藏数量,这是因为您从每个人中选择单个集合,然后对其进行计数。相反,您希望计算所有集合中的Paper个实例 - 您可以使用SelectMany()来实现这一点,而不是将您投射到的集合展平:

(from t in db.Teams
select new TeamPapers 
{
    TeamName = t.Name
    PaperTotal = t.People.SelectMany(p=>p.Papers).Count()
}).ToList()