问题
I am using IDbCommandInterceptor
to catch Entity Framework queries. This way I can access some crucial information such as DbParameter
s and DbCommand
etc.
Bu I also need to get where this query is called from. I have tried to get this by by using StackTrace
:
StackTrace stackTrace = new StackTrace();
System.Reflection.MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
This might work in regular method calls, but in this instance since I am intercepting the Entity Framework mechanism I don't see it is possible to get the calling method in my code.
Is it possible to get the calling method name automatically when an Entity Framework query has run?
回答1:
a bit late, but you were on the right track.
check https://github.com/aspnet/EntityFramework6/issues/657, which will explain how you can get the info from the CallStack.
just a copy/paste from that link:
var stack = new StackTrace(true);
command.CommandText += "\r\n\r\n/********************* \r\n * "
+ string.Join("\r\n * ",
(from f in stack.GetFrames().Skip(2)
let m = f.GetMethod()
select m?.DeclaringType.Name + "." + m?.Name + ":" + f.GetFileLineNumber())
) + "\r\n*********************/";
the downside is that calling the StackTrace on each DB interaction gives a huge performance hit. Be sure to properly test before putting this into any production environment.
来源:https://stackoverflow.com/questions/38048251/catching-calling-method-name-in-idbcommandinterceptor