下面是一個擴展方法,您可以使用它來標記實體框架查詢。它使用WHERE子句,但不應損害性能。
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);
}
}
這裏是如何使用它:
context.Table1.SetQueryName().Where(x => x.C1 > 4)
它將使用調用方法的名稱作爲查詢名稱。
您可以指定另一個名字是這樣的:
context.Table1.SetQueryName("Search for numbers > 4").Where(x => x.Number > 4)
下面是SQL怎麼會是這樣的:
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)