C# 实体框架中的自连接
我希望在实体框架中有以下类型的查询C# 实体框架中的自连接,c#,entity-framework,entity,C#,Entity Framework,Entity,我希望在实体框架中有以下类型的查询 SELECT c2.* FROM Category c1 INNER JOIN Category c2 ON c1.CategoryID = c2.ParentCategoryID WHERE c1.ParentCategoryID is NULL 如何在实体框架中完成上述工作…好吧,我对EF不太了解,但这看起来像: var query = from c1 in db.Category where c1.Par
SELECT c2.*
FROM Category c1 INNER JOIN Category c2
ON c1.CategoryID = c2.ParentCategoryID
WHERE c1.ParentCategoryID is NULL
如何在实体框架中完成上述工作…好吧,我对EF不太了解,但这看起来像:
var query = from c1 in db.Category
where c1.ParentCategoryId == null
join c2 in db.Category on c1.CategoryId equals c2.ParentCategoryId
select c2;
为了整理一下,下面的内容稍微好一点,并且做了同样的事情:
var query = from c1 in db.Category
from c2 in db.Category
where c1.ParentCategoryId == null
where c1.CategoryId == c2.ParentCategoryId
select c2;
在EF 4.0+中,左连接语法有点不同,呈现出一种疯狂的怪癖:
var query = from c1 in db.Category
join c2 in db.Category on c1.CategoryID equals c2.ParentCategoryID
into ChildCategory
from cc in ChildCategory.DefaultIfEmpty()
select new CategoryObject
{
CategoryID = c1.CategoryID,
ChildName = cc.CategoryName
}
如果您在SQL Server Profiler中捕获此查询的执行,您将看到它确实执行了左外部联接。但是,如果在Linq to Entity查询中有多个LEFT JOIN(“Group JOIN”)子句,我发现self JOIN子句实际上可以像在内部JOIN中一样执行—即使使用了上述语法
解决这个问题的决议是什么?根据MS的说法,这听起来很疯狂,也很错误,我通过改变join子句的顺序来解决这个问题。如果自引用的LEFT JOIN子句是第一个Linq组联接,则SQL探查器报告了一个内部联接。如果自引用的LEFT JOIN子句是最后一个Linq组联接,SQL Profiler报告了一个LEFT JOIN。@Waheed:我不知道你的意思-你应该能够在EF中使用这个精确的查询。您好,我已将其更改为return List catergoyList,然后它说你需要强制转换。如何将var强制转换为List对象?@SHEKHARSHETE:您不强制转换它,因为结果不是
List
——而是调用ToList()
,例如return query.ToList()代码>我假设“我需要在EF中”,他可能是指在LINQ表达式中。@Ellesedil:嗯,这是一个LINQ表达式。你怎么认为这不是LINQ表达式?