如何导航多对多关系

时间:2016-03-18 02:01:52

标签: c# entity-framework linq

简化问题:

我有3个表:Person,PersonCreditCard,CreditCard。 一个人有很多信用卡,信用卡属于很多人(是的,我的妻子可以使用我的信用卡:)) 我使用Code First生成类:

public  class Person
    {
        public Person()
        { PersonCreditCard = new HashSet<PersonCreditCard>(); }
        [Key]
        public int BusinessEntityID { get; set; }
        public string FirstName { get; set; }
        public virtual ICollection<PersonCreditCard> PersonCreditCard { get; set; }
}



public partial class PersonCreditCard
{
    [Key]
    [Column(Order = 0)]
    public int BusinessEntityID { get; set; }

    [Key]
    [Column(Order = 1)]
    public int CreditCardID { get; set; }
    public virtual Person Person { get; set; }
    public virtual CreditCard CreditCard { get; set; }
}


public partial class CreditCard
{
    public CreditCard()
    { PersonCreditCard = new HashSet<PersonCreditCard>(); }

    public int CreditCardID { get; set; }
    public string CardType { get; set; }
    public string CardNumber { get; set; }
    public virtual ICollection<PersonCreditCard> PersonCreditCard { get; set; }
}

现在我想按信用卡类型显示人数。在SQL中,很容易:

select count(p.BusinessEntityID), cc.CardType
from Person.Person p
join Sales.PersonCreditCard pcc
on p.BusinessEntityID = pcc.BusinessEntityID
join Sales.CreditCard cc
on cc.CreditCardID = pcc.CreditCardID
group by cc.CardType

但是在Linq to SQL中,我无法弄清楚如何做到这一点。

1 个答案:

答案 0 :(得分:0)

找到了解决方案:

var query = from p in c.Person
            from pcc in p.PersonCreditCard
            group p by new { pcc.CreditCard.CardType } into g
            select new
            {
                cname = g.Key.CardType,
                cptPerson = g.Count()
            };

诀窍是看到linq中的from不是SQL中的from。它&#34;有点&#34;返回一个集合。因此,为了继续使用PersonCreditCard集合的另一面,我需要另一个来定义一个var,我可以用它来跳过该集合的另一面。

任何人都可以指出我对此行为的良好(真实)描述。我想用真实的术语来理解它(我是一名教师,我将在几周后向我的学生解释这一点;)

感谢