LINQ to SQL和自相关表

时间:2010-02-04 23:47:34

标签: c# sql linq-to-sql orm

我们在dbml文件中有以下测试模型:

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吗?

3 个答案:

答案 0 :(得分: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])

答案 1 :(得分: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(),具体取决于您的型号)......我没有方便的分析器窗口。

答案 2 :(得分:0)

试试这个:

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

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