查询标记
查询标记有助于将代码中的 LINQ 查询与日志中捕获的已生成 SQL 查询相关联。
使用新增的 TagWith()
方法对 LINQ 查询进行批注:
提示
可在 GitHub 上查看此文章的示例。
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 中包含的字符串文本。 禁止使用将查询标记用作参数的已编译查询。