クエリのタグ

クエリのタグは、コード内の 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 に含まれる文字列リテラルとして扱われます。 コンパイルされたクエリがパラメーターとしてクエリのタグを受け取ることはできません。