2010-10-14 162 views
0

我有一個實體模型,我一直在尋找寫一個linq查詢,返回每個祖父母的子女和父母的計數。linq:祖父母 - 父母 - 子女查詢

我需要輸出3列:祖父母的名字|孩子的數量|孫子

protected void Page_Load(object sender, EventArgs e) 
{ 
    using (FamilyModel.TheConn myEntities = new FamilyModel.TheConn()) 
    { 
      int TheUserID = 13; // will change later 

      var myOutput = from gparents in myEntities.GrandParents 
        where gparents.UserID == TheUserID 
        select gparent.Name, // here's what's missing: the counts 

      GridView1.DataSource = myOutput; 
      GridView1.DataBind(); 

    } 
} 

我一直在用的SelectMany GROUPBY,奮力聯接....我只是沒有得到結果,我需要爲這個看似簡單的查詢次數。 任何輸入將不勝感激。

感謝

+0

我認爲有關架構更多的信息,將有助於 – Murph 2010-10-14 07:56:55

回答

6
var myOutput = from gparent in myEntities.GrandParents 
       where gparent.UserID == TheUserID 
       select new GrandParentViewModel 
       { 
        Name = gparent.Name, 
        ChildrenCount = gparent.Children.Count(), 
        GrandChildrenCount = gparent.Children.SelectMany(c => c.GrandChildren).Count() 
       }; 

這是假設你Child實體具有導航性能GrandChildren(實際名稱Children世界在這裏做更多的意義 - 孩子們的兒童=孫子)。

在這種情況下,我們預計到GrandParentViewModel

public class GrandParentViewModel 
{ 
    public string Name { get; set; } 
    public int ChildrenCount { get; set; } 
    public int GrandChildrenCount { get; set; } 
} 
+0

結果是出乎意料的:1)名稱顯示爲「它」(智能感知不顯示字段GparentName),2)列顯示數據庫中的子孫總數相同,並且有6行顯示(每個祖輩1行)。它應該顯示每個祖父母的姓名和數量,而不是整個兒童和孫子的總數。這很奇怪。 – user471807 2010-10-14 18:33:28

+0

代碼中有一些拼寫錯誤 - 我將它們編輯出來。應該從'gparent'而不是'從gparents'開始。你有沒有在任何地方偶然定義的變量'gparent'?其次,'myOutput'變量是一個查詢 - 如果你想要一個祖父母(帶有'TheUserId'的祖父母)的結果,你需要調用'myOutput.FirstOrDefault()'。如果你想檢索祖父母列表,請調用'myOutput.ToList()'。 – Yakimych 2010-10-14 19:23:32

+0

哦,我的上帝它工作!!!!!謝謝sooooo了。自從我剛剛接觸linq以來,在過去的3天裏,我一直在努力處理這幾行代碼。你的答案會留在網絡上一段時間,因爲它真的解決了一個問題,我肯定很多人都在努力解決問題,直到他們找到答案。非常感謝你!! – user471807 2010-10-14 20:13:59