Skip to content

ycherkes/EfAbbreviationTagGenerator

Repository files navigation

Stand With Ukraine

EfAbbreviationTagGenerator

NuGet version (EfAbbreviationTagGenerator)

EfAbbreviationTagGenerator is a Roslyn Incremental Source Generator that enhances EF Core LINQ query tracing by generating variable length SQL query tags based on the call site abbreviations.

🛠 Usage

  1. Reference this generator from your project (as an analyzer NuGet package or project reference).
  2. In your LINQ queries, simply call:
query.TagWithCallSiteAbbreviation();
  1. The source generator will automatically emit:
query.TagWith("#mcgu42");

The tag #mcgu42 is generated from a abbreviation of the call site like:

MyClass.GetUsers:L42

🔧 How It Works

  1. Scans all invocations of TagWithCallSiteAbbreviation() in your codebase.
  2. Extracts:
    • File path
    • Method name
    • Line number
  3. Computes an abbreviation.
  4. Emits a helper class:
internal static class AbbreviationTagExtensions
{
    public static IQueryable<T> TagWithCallSiteAbbreviation<T>(
        this IQueryable<T> query,
        [CallerFilePath] string filePath = null,
        [CallerMemberName] string memberName = null,
        [CallerLineNumber] int lineNumber = 0)
    {
        var location = $"{Path.GetFileNameWithoutExtension(filePath)}.{memberName}:L{lineNumber}";
        var hashTag = GetAbbreviationByLocation(location);
        return query.TagWith(hashTag);
    }

    private static string GetAbbreviationByLocation(string location)
    {
        switch (location)
        {
            case "Test0.Main:L38": return "#tm38";
            // ...
            default: return location;
        }
    }
}

📝 Requirements

  • EF Core (uses .TagWith() internally)

Add the following code to your project file to add the generated code to the project folder to be able to find the source code by abbreviation later:

<PropertyGroup>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
    <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
</PropertyGroup>

And then exclude it from compilation

<ItemGroup>
    <!-- Exclude the output of source generators from the compilation -->
    <Compile Remove="$(CompilerGeneratedFilesOutputPath)/**/*.cs" />
</ItemGroup>

Useful links:


📃 License

Apache 2.0

About

EF Core call site abbreviation tag generator

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages