Catching calling method name in IDbCommandInterceptor

旧巷老猫 提交于 2021-02-10 05:06:34

问题


I am using IDbCommandInterceptor to catch Entity Framework queries. This way I can access some crucial information such as DbParameters 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!