繁体   English   中英

实体框架6,命令拦截和存储过程

[英]Entity Framework 6, Command Interception & Stored Procedures

我被要求在我的工作中为系统进行审计。 系统已经完成。 我认为EF 6的Command Intercept应该可以很好地达到我的目的。

但是,在某些情况下,我们想知道是谁发送了请假请求,并且我们希望能够拦截此插入查询。

using (DataContext context = new DataContext())
    {
      var result = context.CreateLeavePrerequest(
        leaveRequest.LeaveType,
        leaveRequest.StartDate,
        leaveRequest.EndDate,
        leaveRequest.NumberOfDays,
        leaveRequest.EmployeeComment,
        leaveRequest.HasSupportingDocumentation,
        leaveRequest.ResourceTag,
        leaveRequest.RemainingBalance,
        leaveRequest.ApproverResourceTag,
        leaveRequest.CapturerResourceTag,
        leaveRequest.SupportingDocumentID,
        ref id
        );

那么存储过程为:

CREATE PROCEDURE [dbo].[CreateLeavePrerequest]
(
  @LeaveType VARCHAR(50) ,
  @StartDate DATETIME ,
  @EndDate DATETIME ,
  @NumberOfDays DECIMAL(18, 5) ,
  @EmployeeComment VARCHAR(512) ,
  @SickNoteIndicator BIT ,
  @ResourceTag INT,
  @RemainingBalance DECIMAL,
  @ApproverResourceTag INT,
  @CapturerResourceTag INT,
  @SupportingDocumentID INT,
  @id INT = 0 OUT
)  
AS 
BEGIN
    INSERT  INTO [ESS PER LVE PreRequest]
            ( [Resource Tag] ,
              [Leave Type] ,
              [Start Date] ,
              [End Date] ,
              [No Of Days] ,
              [Employee Comments] ,
              [Sick Note Indicator],
              [Status],
              [Remaining Balance],
              [Approver Resource Tag],
              [Capturer Resource Tag],
              [SupportingDocumentID]
            )
            SELECT  @ResourceTag ,
                    @LeaveType ,
                    @StartDate ,
                    @EndDate ,
                    @NumberOfDays ,
                    @EmployeeComment ,
                    @SickNoteIndicator,
                    'Captured',
                    @RemainingBalance,
                    @ApproverResourceTag,
                    @CapturerResourceTag,
                    @SupportingDocumentID;
SELECT @id
END 

更新:

CreateLeavePrerequest的实现如下:

public ISingleResult<CreateLeavePrerequestResult> CreateLeavePrerequest([global::System.Data.Linq.Mapping.ParameterAttribute(Name="LeaveType", DbType="VarChar(50)")] string leaveType, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="StartDate", DbType="DateTime")] System.Nullable<System.DateTime> startDate, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="EndDate", DbType="DateTime")] System.Nullable<System.DateTime> endDate, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="NumberOfDays", DbType="Decimal(18,5)")] System.Nullable<decimal> numberOfDays, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="EmployeeComment", DbType="VarChar(512)")] string employeeComment, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="SickNoteIndicator", DbType="Bit")] System.Nullable<bool> sickNoteIndicator, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="ResourceTag", DbType="Int")] System.Nullable<int> resourceTag, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="RemainingBalance", DbType="Decimal(18,0)")] System.Nullable<decimal> remainingBalance, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="ApproverResourceTag", DbType="Int")] System.Nullable<int> approverResourceTag, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="CapturerResourceTag", DbType="Int")] System.Nullable<int> capturerResourceTag, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="SupportingDocumentID", DbType="Int")] System.Nullable<int> supportingDocumentID, [global::System.Data.Linq.Mapping.ParameterAttribute(DbType="Int")] ref System.Nullable<int> id)
    {
        IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), leaveType, startDate, endDate, numberOfDays, employeeComment, sickNoteIndicator, resourceTag, remainingBalance, approverResourceTag, capturerResourceTag, supportingDocumentID, id);
        id = ((System.Nullable<int>)(result.GetParameterValue(11)));
        return ((ISingleResult<CreateLeavePrerequestResult>)(result.ReturnValue));
    }

更新2

在Global.asax中注册DBCommandInterceptor:

 protected void Application_Start()
 {
     DbInterception.Add(new Auditor());
 }

DBCommandInterceptor的实现:

我迅速实现了这一点,以便可以看到是否可以拦截任何内容,因此它可以写入“调试”窗口。 我已经能够拦截一些Select查询,但这不是我们要审核的内容。

 public class Auditor : IDbCommandInterceptor
{
    public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        CreateAuditMessage(command, interceptionContext);
    }

    public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        CreateAuditMessage(command, interceptionContext);
    }

    public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        CreateAuditMessage(command, interceptionContext);
    }

    public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        CreateAuditMessage(command, interceptionContext);
    }

    public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        CreateAuditMessage(command, interceptionContext);
    }

    public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        CreateAuditMessage(command, interceptionContext);
    }

    public static void CreateAuditMessage<T>(DbCommand command, DbCommandInterceptionContext<T> interceptionContext)
    {
        string message;

        var parameters = new StringBuilder();
        foreach (DbParameter param in command.Parameters)
        {
            parameters.AppendLine(param.ParameterName + " " + param.DbType + " = " + param.Value);
        }

        if (interceptionContext.Exception == null)
        {
            message = (parameters.ToString() + "  " + command.CommandText);
        }
        else
        {
            message =  (parameters.ToString() + command.CommandText + "  " + interceptionContext.Exception);
        }

        Debug.WriteLine(message);
    }
}

最近,我读了很多关于实体框架的文章,但是我不是很了解。 我已经实现了IDbCommandInterface并进行了注册,等等。我能够看到其他一些查询被拦截,但是由于上述情况使得存储过程被称为“外部”,因此无法获取参数。

这是一个简单的例子。 并非系统中以类似方式调用的所有存储过程都这么简单。

改变上述情况以使我们可以应用拦截并进行审核的最佳方法是什么?

我更喜欢下面的方法从我的应用程序执行SQL存储过程,因为我也使用这种方法从远程服务器执行存储过程。 您唯一需要注意的是将正确格式的参数传递给相应的Parameter类型。

using (SqlConnection con = new SqlConnection(dc.Con)) {
   using (SqlCommand cmd = new SqlCommand("CreateLeavePrerequest", con)) {
       cmd.CommandType = CommandType.StoredProcedure;

       cmd.Parameters.Add("@LeaveType", SqlDbType.VarChar).Value = leaveType;
       cmd.Parameters.Add("@StartDate", SqlDbType.VarChar).Value = startDate;
       cmd.Parameters.Add("@EndDate", SqlDbType.VarChar).Value = endDate;
       cmd.Parameters.Add("@NumberOfDays", SqlDbType.VarChar).Value = numberOfDays;
       cmd.Parameters.Add("@EmployeeComment", SqlDbType.VarChar).Value = employeeComment;
       cmd.Parameters.Add("@SickNoteIndicator", SqlDbType.VarChar).Value = sickNoteIndicator;
       cmd.Parameters.Add("@ResourceTag", SqlDbType.VarChar).Value = resourceTag;
       cmd.Parameters.Add("@RemainingBalance", SqlDbType.VarChar).Value = remainingBalance;
       cmd.Parameters.Add("@ApproverResourceTag", SqlDbType.VarChar).Value = approverResourceTag;
       cmd.Parameters.Add("@CapturerResourceTag", SqlDbType.VarChar).Value = capturerResourceTag;
       cmd.Parameters.Add("@SupportingDocumentID", SqlDbType.VarChar).Value = supportingDocumentID;
       cmd.Parameters["@id"].Direction = ParameterDirection.Output; 

       con.Open();
       cmd.ExecuteNonQuery();
  }
}

对于任何NULL值,请检查

DBNull.Value

让我知道是否有帮助。 谢谢!

您始终可以使用Context Log属性来使用DataContext拦截任何数据库查询触发

您可以在DataContext类上定义一个构造函数,如下所示。

public class DataContext : DbContext, IDataContext
{

    public DataContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
          Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
          //NOTE: Instead of Debug.WriteLine, you can stroe it in DB.

    }
.....
.....
.....
}

上下文日志属性记录了什么?

  • 适用于各种命令的SQL。 例如:

    1-查询,LINQ查询,eSQL查询和原始查询。

    2-在SaveChanges中生成的插入,更新和删除

    3-关系加载查询,例如由延迟加载生成的查询

  • 参量
  • 命令是否异步执行
  • 指示命令何时开始执行的时间戳
  • 命令是否成功完成,是否因引发异常而失败,或者对于异步而言,已被取消
  • 一些指示结果值
  • 执行命令所花费的大概时间。 请注意,这是从发送命令到取回结果对象的时间。 它不包括读取结果的时间。

了解更多信息。 记录到不同的地方,结果记录,格式化等,可以检查记录和拦截数据库操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM