如何将此实体框架查询转换为SQL Server查询

时间:2020-10-09 06:19:47

标签: c# sql sql-server entity-framework

我有一个查询,其格式如下:

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查询以查看其输出是什么?

2 个答案:

答案 0 :(得分:3)

在Entity Framework中,有几种方法可以查看查询生成的SQL。

注意:所有这些方式都将使用此查询:

pack1 is empty
============================
doc is docum2
pack is package2
============================
doc is docum102222
pack is package30234324
  1. 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并获取其跟踪字符串:
ObjectQuery
  1. 拦截日志记录并将其打印到// 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
  1. 实体框架配置。
    如果您使用的是EF 6.1及更高版本,则可以使用EF配置创建拦截器,并将其记录到txt文件中,如here所述:
// 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
  1. 最后,您可以使用LinqPad。有一个免费版本可以连接到数据库,您可以在其中直接输入C#表达式或语句并在底部显示生成的SQL,类似于此Screenshot of LinqPad 6

答案 1 :(得分:0)

可以将DbContext.Database.Log属性设置为任何采用字符串的方法的委托。在此示例中,SQL语句使用Console.Write

写入控制台。
using (var context = new BlogContext())
{
    context.Database.Log = Console.Write;
    var blog = context.Blogs.First(b => b.Title == "One Unicorn");
    blog.Posts.First().Title = "Green Eggs and Ham";
    blog.Posts.Add(new Post { Title = "I do not like them!" });
    context.SaveChangesAsync().Wait();
}

来自:https://docs.microsoft.com/en-us/ef/ef6/fundamentals/logging-and-interception