c# - LINQ to SQL 和自关联表

标签 c# sql linq-to-sql orm

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

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

对于测试用例,表中有 4 条记录,1 个 parent ,3 个 child 。我们正在寻找特定记录的 sibling ,包括特定记录。

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,我们是否应该采用另一种方法来解决这个问题?

最佳答案

您可以在 Linq 查询中堆叠 from 语句,这可能会对您有所帮助。

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])

关于c# - LINQ to SQL 和自关联表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2204098/

相关文章:

c# - Json 无法解析 ajax post 请求

c# - 查找文件文件夹的最新最后修改时间的最佳方法是什么?

c# - 从法师签名的 list 文件中获取 X509 证书

sql - 如何将列表存储在数据库表的列中

c# - Linq to sql - 数据库不会更新

c# - Windows 8 商店应用程序不支持 System.Threading.Thread

php - 有效的 PHP 数组和选择

mysql - SQL连接并计算行数

mysql - mysql v 3.23 中的嵌套选择

用于比较 LINQtoSQL 等值的 C# 表达式