在IDbCommandInterceptor中捕获调用方法名称

在IDbCommandInterceptor中捕获调用方法名称

本文介绍了在IDbCommandInterceptor中捕获调用方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 IDbCommandInterceptor 来捕获实体框架查询.这样,我可以访问一些关键信息,例如 DbParameter s和 DbCommand 等.

I am using IDbCommandInterceptor to catch Entity Framework queries. This way I can access some crucial information such as DbParameters and DbCommand etc.

Bu我还需要获取调用此查询的位置.我试图通过使用 StackTrace 来获得此功能:

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();

这可能在常规方法调用中起作用,但是在这种情况下,由于我拦截了Entity Framework机制,因此我看不到有可能在我的代码中获得调用方法.

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.

运行Entity Framework查询时是否可以自动获取调用方法的名称?

Is it possible to get the calling method name automatically when an Entity Framework query has run?

推荐答案

有点晚,但是您走在正确的轨道上.

a bit late, but you were on the right track.

检查 https://github.com/aspnet/EntityFramework6/issues/657,这将说明如何从CallStack中获取信息.

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*********************/";

缺点是,在每次数据库交互时调用StackTrace都会对性能造成巨大影响.在将其投入任何生产环境之前,请务必进行正确的测试.

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.

这篇关于在IDbCommandInterceptor中捕获调用方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:41