简体   繁体   English

将SQL转换为LINQ to SQL

[英]Convert SQL to LINQ to SQL

I have the SQL query 我有SQL查询

with c as (
  select  categoryId,parentId, name,0 as [level]
  from task_Category b 
  where b.parentId is null
    union all
  select b.categoryId,b.parentId,b.name,[level] + 1
  from task_Category b join c on b.parentId = 
    c.categoryId)
select name,[level],categoryId,parentId 
  as item 
from c

and I want to convert it to LINQ to SQL, yet my LINQ skills are not there yet. 我想将它转换为LINQ to SQL,但我的LINQ技能还没有。 Could someone please help me convert this. 有人可以帮我转换一下。 It's the with and union statements that are making this a bit more complex for me. with和union语句使我对此更加复杂。

Any help appreciated. 任何帮助赞赏。

That is a recursive CTE . 那是一个递归的CTE LINQ to SQL does not support recursive CTEs yet (and probably never will). LINQ to SQL还不支持递归CTE(并且可能永远不会)。 Sorry! 抱歉!

As a workaround you can leave the query as it is in SQL and put it in a stored procedure. 作为一种解决方法,您可以将查询保留在SQL中,并将其放在存储过程中。 You can then call that stored procedure from LINQ to SQL. 然后,您可以将该存储过程从LINQ调用到SQL。

LINQ-to-SQL only supports basic queries; LINQ-to-SQL仅支持基本查询; CTE and recursion are not included in this. CTE和递归不包括在内。 Therefore, here's my high-tech translation to LINQ-to-SQL: 因此,这是我对LINQ-to-SQL的高科技翻译:

var data = ctx.ExecuteQuery<MyStub>(@"
with c as (
  select  categoryId,parentId, name,0 as [level]
  from task_Category b 
  where b.parentId is null
    union all
  select b.categoryId,b.parentId,b.name,[level] + 1
  from task_Category b join c on b.parentId = 
    c.categoryId)
select name,[level],categoryId,parentId 
  as item 
from c").ToList();

with

class MyStub {
    public string name {get;set;}
    public int level {get;set;}
    public int categoryId {get;set;}
    public int parentId {get;set;}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM