c# - 如何将此实体框架查询转换为 SQL Server 查询
问题描述
我有一个查询,其格式如下:
bool filterQuotes = false;
bool filterInactive = false;
var res = await DbContext.CheckPlans
.Where(plan => plan.PlanID == currentPlanId)
.SelectMany(plan => plan.CheckActivityPlanDetail)
.Include(planDetail => planDetail.CheckActivity)
.ThenInclude(checkActivity => checkActivity.Setup)
.Where(planDetail => (!filterQuotes || planDetail.CheckActivity.ActivityType==0)
&& (!filterInactive || planDetail.IsActive))
.OrderBy(planDetail => planDetail.CheckActivity.Setup.Value)
.ToListAsync();
如何将此查询转换为普通 SQL Server 查询以查看其输出是什么?
解决方案
在 Entity Framework 中,有几种方法可以查看查询生成的 SQL。
注意:所有这些方式都将使用此查询:
var query = DbContext.CheckPlans
.Where(plan => plan.PlanID == currentPlanId)
.SelectMany(plan => plan.CheckActivityPlanDetail)
.Include(planDetail => planDetail.CheckActivity)
.ThenInclude(checkActivity => checkActivity.Setup)
.Where(planDetail => (!filterQuotes || planDetail.CheckActivity.ActivityType==0)
&& (!filterInactive || planDetail.IsActive))
.OrderBy(planDetail => planDetail.CheckActivity.Setup.Value);
- 转换
IQueryable
为 anObjectQuery
并获取它的跟踪字符串:
// ObjectQuery is in the 'System.Data.Objects' namespace if EF version < 6
// starting with EF version 6 and upwards it's in the 'System.Data.Entity.Core.Objects' namespace
var sql = ((ObjectQuery) query).ToTraceString();
- 拦截日志并将其打印到
Debug.WriteLine
:
// This code needs to be placed where you are creating your DbContext
context.Database.Log = s => Debug.WriteLine(s);
// ...
// Then when executing the query with
var results = query.ToListAsync();
// Your debug console in Visual Studio should contain all the information you need
- 实体框架配置。
如果您使用的是 EF 6.1 及更高版本,则可以使用 EF 配置创建拦截器并将其记录到 txt 文件中,如下所述:
<interceptors>
<interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
<parameters>
<parameter value="C:\Temp\LogOutput.txt"/>
<parameter value="true" type="System.Boolean"/>
</parameters>
</interceptor>
</interceptors>
- 最后,您可以使用LinqPad。有一个可以连接数据库的免费版本,可以直接输入C#表达式或语句,生成的SQL会显示在底部,类似这样
推荐阅读
- java - 如何使 70 字节的 .class 文件打印“Hello World”?
- php - 为什么在 Laravel 5.6 中没有突出显示当前的引导菜单?
- javascript - 如何以引导程序 ngb-tabset 的角度 6 以编程方式加载选项卡
- windows - 使用 bazel 在 Windows 上构建 tensorflow r1.12 mkl,导致链接错误
- node.js - Angular 2文件上传错误与node.js
- excel - Excel最小化时如何自动输入数据?
- python-3.x - "__new__" 创建一个无限递归循环
- javascript - Outlook 桌面应用程序加载项,用于将邮件地址插入 Outlook 新邮件到地址栏
- objective-c - 通过 iOS 应用程序中的代理引导流量
- php - 如何使用php发送包含其他输入的表单的可排序列表值