2015-08-27 39 views
0

我有如何在LINQ方法和語法中選擇Distinct/Group通過child屬性?

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; } 
} 

我需要的東西,相當於

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

而且

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

任何幫助將不勝感激。由於

回答

1

沒有理由加入到父,因爲你可以只使用Child.ParentId

無論如何,你可以這樣做:

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

或不加入;

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

和獨特的無非是:

var result = db.Set<Child>().Where(c => c.ParentId = 1).Select(c => c.Grade).Distinct(); 
相關問題