当CommandType为StoredProcedure时,如何使用IDbCommandInterceptor修改SQL
本文关键字:何使用 IDbCommandInterceptor 修改 SQL CommandType StoredProcedure | 更新日期: 2023-09-27 18:17:35
我正在使用实体框架6,并希望在对数据进行任何修改之前设置CONTEXT_INFO
,因此我的审计触发器可以记录哪个用户进行了修改。似乎可以使用IDbCommandInterceptor
来改变将要执行的CommandText
,就像下面的代码一样。但是如果DbCommand.CommandType == CommandType.StoredProcedure
那么它不喜欢这样,因为它期望CommandText
将是只是过程名,并且如果我用额外的SQL前缀它就会抛出错误。
public class SetContextInterceptor : IDbCommandInterceptor
{
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
command.CommandText = GetSqlForSetContextInfo() + command.CommandText;
}
// ... other interface methods similar
private string GetSqlForSetContextInfo()
{
var currentUsername = Thread.CurrentPrincipal != null && Thread.CurrentPrincipal.Identity != null
? Thread.CurrentPrincipal.Identity.Name
: null;
if (String.IsNullOrEmpty(currentUsername))
{
return "";
}
return "EXEC usp_setUserContext '" + currentUsername.Replace('''', ' ') + "'; ";
}
}
特别是在这种情况下,参数不在CommandText
中(即CommandText只包含存储过程名称),所以我不想进入为参数做字符串操作的混乱业务。这个案子有简单的处理方法吗?
这里有一些关于CONTEXT_INFO
实现类似目标的其他文章。似乎在这个主题上有很多变化,但没有达成一致的方法,许多技术都是在ef6之前,所以没有IDbCommandInterceptor
选项。
使用实体框架记录每次数据更改
如何从Devforce IdeaBlade应用程序设置context_info sql语句
http://forum.ideablade.com/forum_posts.asp?TID=3855& PID = 15476,标题= value-cannot-be-null-getting-ientityqueryt-when-using-usepersistentdbconnectionpersession # 15476
https://social.msdn.microsoft.com/forums/en us/19065701 - 6脂肪酸- 4740 - acca b0e5312ca4f4/am -我-泄漏dbcontext -对象-处理- statechange?forum=adodotnetentityframeworkhttp://itq.nl sql-azure-row-level-security-entity-framework/
http://blogs.msmvps.com/p3net/2013/09/13/entity-framework-and-user-context/- http://davecallan.com/passing-userid-delete-trigger-entity-framework
我猜,因为它是不可能得到的'SQL',当CommandType = StoredProcedure,这是不可能操纵它执行。我想到的选项(对于我想设置CONTEXT_INFO的场景)是抓住command.Connection
并执行单独的命令来设置CONTEXT_INFO。我不确定这会有多好,例如,如果连接还没有打开,那么我必须自己打开它。
从。net我可以得到由SqlCommand对象(与SQL参数)生成的完整SQL字符串吗?
根据我上面的UPDATE,我决定这是不可能的。