2012-02-16 103 views
0

我正在使用Linq To Sql的WP7應用程序。我已經使用Linq,但這是我第一次使用Linq to Sql。我在過濾EntitySet中的數據時遇到問題。我可能做錯了我不知道。我現在有的工作,但我需要得到一個過濾的EntitySets。LinqToSql篩選器實體集

我有4張桌子。 Parent,Child,Grandchild和ParentChild鏈接表。當我查詢ParentChild時,我找回了ParentChild實體,並且可以遍歷Parent,Child和Grandchild實體。我想要做的就是過濾孫子實體。

可以說我在父表中有一個父親和母親。然後我在兒童桌上有一個兒子和女兒。然後是孫子孫女中的孫子和孫女。當然,有正常的協會等等。

我想要返回父親,這也讓我所有關聯的表很好。我有的問題是過濾孫子。假設我只想要孫子,並且有一個性愛領域。我怎樣才能做到這一點?我似乎無法弄清楚。

這裏是我使用的代碼工作正常,但它拉動所有的孫子。

IQueryable<ParentChild> parentChild = from ParentChild c in DataContext.ParentChild 
               where c.ParentId == this.parentId 
               select c; 

foreach (Grandchild grandchild in parentChild.SelectMany(parent => parent.Child.Grandchild)) 
{ 
    Console.WriteLine(grandchild.Name); 
} 

所以,如果我這樣做:

IQueryable<ParentChild> parentChild = from ParentChild c in DataContext.ParentChild 
             where c.ParentId == this.parentId && c.Child.Grandchild.Any(a => a.Sex == "F") 
             select c; 

foreach (Grandchild grandchild in parentChild.SelectMany(parent => parent.Child.Grandchild)) 
{ 
    Console.WriteLine(grandchild.Name); 
} 

我得到了家長,但我只得到有女孫輩孩子。我希望父母,所有的孩子(即使他們沒有女性孫輩或沒有任何孫輩),也只有女性孫子女。

回答

1

經過多次試驗和錯誤和搜索,我找到了答案。我必須使用AssociateWith選項。

DataLoadOptions dataLoadOptions = new DataLoadOptions(); 
dataLoadOptions.AssociateWith<Child>(c => c.Grandchild.Where(p => p.Sex == "F")); 

this.DataContext.LoadOptions = dataLoadOptions; 
+0

這正是我所追求的,需要更多的讚揚! – Ian 2016-01-07 02:06:07

0

只要你在SQL中正確設置了外鍵; LINQ to SQL將能夠爲您提供與您的外鍵關係相匹配的關聯屬性。

如果你的外鍵設置,你就可以做到以下幾點...

var query = from p in DataContext.Parent    
      //make sure they have at least 1 female grandchild 
      where p.GrandChilds.Any(gc => gc.IsFemale) 
      select p; 

我做了關於你的數據模型的名稱一些假設,但你的想法。 :-)

+0

謝謝你讓我走向正確的方向。我很感激。 – vincentw56 2012-02-17 00:52:44

+0

我似乎現在唯一遇到的問題是,它將拉大孫子的罰款,但它只拉扯與孫子有關的一個孩子。我希望能夠把所有孩子的父親,所有的孩子和所有的女性孫輩都拉下來。 – vincentw56 2012-02-17 01:01:31