2010-02-04 55 views
3

我們在DBML文件中的下列測試模型:LINQ to SQL和自相關表

Model http://www.freeimagehosting.net/uploads/a86582498a.gif

測試用例有4條表中的記錄,1個父,3個孩子。我們正在尋找特定記錄的兄弟姐妹,包括具體記錄。

using (var db = new TestDataContext()) 
{ 
    var query = 
     from f in db.Foos 
     where f.Name == "Two" 
     select f.Foo1.Foos;    // get the record's parent's children 

    var foos = query.SelectMany(f => f); // project the EntitySet 

    Assert.AreEqual(3, foos.Count()); // passes 
} 

這將返回正確的項目有以下SQL:

SELECT  [t2].[FooId], 
      [t2].[ParentFooId], 
      [t2].[Name] 
FROM  [dbo].[Foos] AS [t0] 
INNER JOIN [dbo].[Foos] AS [t1] ON [t1].[FooId] = [t0].[ParentFooId] 
CROSS JOIN [dbo].[Foos] AS [t2] 
WHERE  ([t0].[Name] = @p0) 
AND  ([t2].[ParentFooId] = [t1].[FooId]) 

我們想知道的CROSS JOIN,這顯然是中的SelectMany的結果?
有沒有另一種方法,我們應該這樣做,以便沒有CROSS JOIN?

回答

0

你可以做交替:

var query = from f in db.Foos 
      where (from fo in db.Foos 
        where fo.Name == "Two" 
        select fo.ParentId).Contains(f.ParentId) 
      select f; 

這將導致類似:

SELECT  [t1].[FooId], 
      [t1].[ParentFooId], 
      [t1].[Name] 
FROM  [dbo].[Foos] AS [t1] 
WHERE  [t1].[ParentFooId] IN (SELECT [t0].[ParentFooId] 
            FROM [dbo].[Foos] AS [t0] 
            WHERE[t0].[Name] = @p0) 

可能不同位(可能是Exists()取決於你的模型)......我不知道有一個方便的探查器窗口。

1

您可以從Linq查詢中的語句進行堆棧,這可能會幫助您在這裏。

var query = from f in db.Foos 
      from f2 in f.Foos 
      where f.Name == "Two" 
      select f2; 

哪產生。

SELECT [t1].[FooId], 
     [t1].[Name], 
     [t1].[ParentFooId] 
FROM [dbo].[Foos] AS [t0], [dbo].[Foos] AS [t1] 
WHERE ([t0].[Name] = @p0) AND ([t1].[ParentFooId] = [t0].[FooId]) 
+0

因此,這是怎麼回事未指定離開,因爲一個聯合起來到SQL Server的類型? – blu 2010-02-05 14:43:52

+0

是的。默認情況下,這是一個內部聯接。 – 2010-02-05 20:26:07

+0

這是我的理解,','將離開確定加入到SQL Server;它可能是內部連接,也可能是交叉連接。如果沒有提到那個實施會很好。 – blu 2010-02-13 06:48:31

0

試試這個:

var siblings = DataContext.Foos.Where(a => a.FooID == 3) 
    .Select(b => Foos.Where(b => Foos.ParentFooID == a.ParentFooID)); 

Assert.AreEqual(3, siblings.Count()); 
+0

你錯過了大括號! – 2010-02-05 06:55:13

+0

謝謝你的收穫。 – 2010-02-05 06:56:41