我有一个查询,其格式如下:
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查询以查看其输出是什么?
答案 0 :(得分:3)
在Entity Framework中,有几种方法可以查看查询生成的SQL。
注意:所有这些方式都将使用此查询:
pack1 is empty
============================
doc is docum2
pack is package2
============================
doc is docum102222
pack is package30234324
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
// 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
答案 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