Here is an extension method that you can use to mark Entity Framework queries:
public static class ExtensionMethods { public static IQueryable<T> SetQueryName<T>(this IQueryable<T> source, [CallerMemberName] String name = null, [CallerFilePath] String sourceFilePath = "", [CallerLineNumber] Int32 sourceLineNumber = 0) { var expr = Expression.NotEqual(Expression.Constant("Query name: " + name), Expression.Constant(null)); var param = Expression.Parameter(typeof(T), "param"); var criteria1 = Expression.Lambda<Func<T, Boolean>>(expr, param); expr = Expression.NotEqual(Expression.Constant($"Source: {sourceFilePath} ({sourceLineNumber})"), Expression.Constant(null)); var criteria2 = Expression.Lambda<Func<T, Boolean>>(expr, param); return source.Where(criteria1).Where(criteria2); } }
Here's how to use it:
context.Table1.SetQueryName().Where(x => x.C1 > 4)
It will use the name of the calling method as the name of the request.
You can specify a different name like this:
context.Table1.SetQueryName("Search for numbers > 4").Where(x => x.Number > 4)
This is what SQL looks like:
SELECT [Extent1].[Number] AS [Number] FROM (SELECT [Table1].[Number] AS [Number] FROM [dbo].[Table1] AS [Table1]) AS [Extent1] WHERE (N'Query name: Search for numbers > 4' IS NOT NULL) AND (N'Source: C:\Code\Projects\MyApp\Program.cs (49)' IS NOT NULL) AND ([Extent1].[Number] > 4)
source share