How to select Distinct / Group By child property in both LINQ method and syntax?

c# entity-framework entity-framework-6 linq

Question

I'm in class.

public class Parent
{
    [Key]
    public int ParentID { get; set;}
    public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
    [Key]
    public int ChildID { get; set; }
    public int Grade { get; set; }
    public int ParentID { get; set; }

    [ForeignKey("ParentID")]
    public virtual Parent Parent { get; set; }
}

I require an equivalent of

SELECT
    Child.Grade
FROM
    Parent
    INNER JOIN Child ON
        Parent.ParentID = Child.ParentID
WHERE
    Parent.ParentID = 1
GROUP BY
    Child.Grade

And

SELECT DISTINCT
    Child.Grade
FROM
    Parent
    INNER JOIN Child ON
        Parent.ParentID = Child.ParentID
WHERE
    Parent.ParentID = 1

I would appreciate any assistance. Thanks

1
0
8/27/2015 3:09:47 AM

Accepted Answer

There is no need to connect the parent since you can simply useChild.ParentId

In any case, you could:

var result = db.Set<Child>().Where(c => c.Parent.ParentId = 1).GroupBy(c => c.Grade);

the join; or not;

var result = db.Set<Child>().Where(c => c.ParentId = 1).GroupBy(c => c.Grade);

And distinctive is just:

var result = db.Set<Child>().Where(c => c.ParentId = 1).Select(c => c.Grade).Distinct();
1
8/27/2015 3:21:06 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow