• EF Core中如何使用TagWith()方法追踪其生成的SQL语句
  • 发布于 2个月前
  • 183 热度
    0 评论
概述
在使用EF Core的时候,有时候我们需要追踪它生成的sql语句,那么方法那么多,我们怎么知道对应的sql语句是在代码哪里呢,这时候就需要一个备注,

TagWith()能够帮助我们生成对应的注释信息。查询标记有助于将代码中的LINQ查询与日志中捕获的生成的SQL查询相关联。您使用新TagWith()方法注释LINQ查询:EF Core 2.2+中的TagWith是一项出色的功能,可以跟踪查询存储区中的查询,但您必须记住将其添加到所有查询中。

实现方法
// 堆代码 duidaima.com
var myLocation = new Point(1, 2);
var nearestPeople = (from f in context.People.TagWith("This is my spatial query!")
                     orderby f.Location.Distance(myLocation) descending
                     select f).Take(5).ToList();
此LINQ查询被转换为以下SQL语句:
-- This is my spatial query!

SELECT TOP(@__p_1) [p].[Id], [p].[Location]
FROM [People] AS [p]
ORDER BY [p].[Location].STDistance(@__myLocation_0) DESC
可以TagWith()在同一查询上多次调用。查询标签是累积的。例如,给定以下方法:
private static IQueryable<Person> GetNearestPeople(SpatialContext context, Point myLocation)
    => from f in context.People.TagWith("GetNearestPeople")
       orderby f.Location.Distance(myLocation) descending
       select f;

private static IQueryable<T> Limit<T>(IQueryable<T> source, int limit) => source.TagWith("Limit").Take(limit);
以下查询:
var results = Limit(GetNearestPeople(context, new Point(1, 2)), 25).ToList();
转换为:
-- GetNearestPeople

-- Limit

SELECT TOP(@__p_1) [p].[Id], [p].[Location]
FROM [People] AS [p]
ORDER BY [p].[Location].STDistance(@__myLocation_0) DESC
也可以使用多行字符串作为查询标签。例如:
var results = Limit(GetNearestPeople(context, new Point(1, 2)), 25).TagWith(
                    @"This is a multi-line
string").ToList();
产生以下SQL:
-- GetNearestPeople

-- Limit

-- This is a multi-line
-- string

SELECT TOP(@__p_1) [p].[Id], [p].[Location]
FROM [People] AS [p]
ORDER BY [p].[Location].STDistance(@__myLocation_0) DESC
查询标签不可参数化:EF Core始终将LINQ查询中的查询标签视为包含在生成的SQL中的字符串文字。不允许将查询标记作为参数的已编译查询。
用户评论