I have 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 need something 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
Any help will be appreciated. Thanks
There's no reason to join to the parent, because you can just use Child.ParentId
Anyway, you can do this:
var result = db.Set<Child>().Where(c => c.Parent.ParentId = 1).GroupBy(c => c.Grade);
Or without the join;
var result = db.Set<Child>().Where(c => c.ParentId = 1).GroupBy(c => c.Grade);
And distinct is simply:
var result = db.Set<Child>().Where(c => c.ParentId = 1).Select(c => c.Grade).Distinct();