我们在 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/