在linq中自我加入条件写多个

时间:2017-02-09 08:07:16

标签: linq-to-sql

我无法将此sql查询写入linq.can任何正文请求帮助。谢谢提前

 select catp.Name from Article art join Categorys cat on art.CategoryId=cat.CategoryId join Categorys catp
 on cat.ParentCategoryId=catp.CategoryId or cat.CategoryId = catp.CategoryId where ArticleId=24

1 个答案:

答案 0 :(得分:0)

您提供的查询有点令人困惑。为什么你加入了Categorys catp并写了加入条件"或cat.CategoryId = catp.CategoryId"。它将给出与以下查询相同的结果:

select cat.Name from Article art 
join Categorys cat on art.CategoryId=cat.CategoryId 
where ArticleId=24

现在在上面的查询中编写Linq应该很简单。如果想过滤分类中ParentCategoryId = CategoryId的项目,那么它应该是:

select cat.Name from Article art 
join Categorys cat on art.CategoryId=cat.CategoryId 
where ArticleId=24 and cat.ParentCategoryId = cat.CategoryId 

的LINQ:

var result = (from cat in Categories
                join art in Articals
                    on cat.CategoryId equals art.CategoryId
                where art.CategoryId == 24 && cat.CategoryId == cat.ParentCategoryId
                select cat.Name).ToList()