c# - 将 Sql 语句转换为 Entity Framework Core
问题描述
如何将此 sql 查询转换为实体框架核心中的 linq?
Select a.Id,a.Url,c.Title,a.ParentId,b.totalSubCats
From [Tbl_Menu] As a
LEFT OUTER JOIN
( Select ParentId, Count(*) As totalSubCats From [Tbl_Menu] Group By ParentId ) As b
On a.Id=b.ParentId
LEFT OUTER JOIN [Tbl_Menu] As c On a.Id = c.Id
ORDER BY a.Id
我们有这些列Menu_Tbl
Id
, Url
, Title
, Description
,ParentId
因为Left Join
我写了这个查询但不能运行
var query = (from m1 in _context.Menu_Tbl
join m2 in _context.Menu_Tbl on m1.Id equals m2.Id
into m3 from m in m3.DefaultIfEmpty() select m1);
解决方案
这个应该可以的。只需将大查询除以小块(子查询)
var grouped =
from m in ctx.Tbl_Menu
group m by new { m.ParentId } into g
select new
{
g.Key.ParentId,
totalSubCats = g.Count()
};
var query =
from a in ctx.Tbl_Menu
join b in grouped on a.Id equals b.ParentId into gj
from b in gj.DefaultIfEmpty()
join c in ctx.Tbl_Menu on a.Id equals c.Id into ggj
from c in ggj.DefaultIfEmpty()
select new
{
a.Id,
a.Url,
c.Title,
a.ParentId,
b.totalSubCats
};
推荐阅读
- sql - 带有变量的 SQL 前缀问题 N
- dns - Terraform / Route53 中的 CNAME 别名
- java - 在自动化测试期间,带有 select 的输入保持为空
- scala - 值 toDF 不是 org.apache.spark.rdd.RDD[(K, V)] 的成员
- java - “新 XSSFWorkbook”在 IntelliJ 中不起作用
- java - TextView 不 setText 里面包含布局
- r - 替换字符串中的下标数字
- java - 尝试将 Maven 构建 JAR 部署到 github 包注册表时出现异常
- big-o - 大 O 符号的 PA
- postgresql - SaltStack:在特定更改时重新启动服务器(不仅重新加载)