I have a query which is written in format like this:
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();
How do I convert this query to a plain SQL Server query to see what its output is?
In Entity Framework there are a few ways to look at the SQL a query generates.
Note: All these ways will use this query:
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 to an ObjectQuery and get it's trace string:// 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
<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>

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With