1

我正在使用 EF 6 并尝试使用 System.Data.Entity.Infrastructure.Interception 命名空间中的 IDbCommandInterceptor。

它适用于读取和更新,但是当我向数据库添加新实体时,NonQueryExecuted() 不会触发,NonQueryExecuting() 也不会触发。这是拦截器的正常行为还是我没有正确实施?

代码:

拦截器:

    public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            this.MonitorAndNotifySignalRService(command);
        }

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

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

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

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

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

数据上下文库:

        static Constructor()
    {
        Database.SetInitializer<TDataContext>(null);        // turn off database initialization so the db schema is not changed from the model
        DbInterception.Add(new Interceptor());
    }
4

1 回答 1

4

这是设计使然。当插入具有数据库生成标识的实体时,插入语句会附带一条SELECT语句,用于将生成的标识值读入插入实体的 Id 属性。该命令具有以下形状:

INSERT [dbo].[Table](...)
VALUES (...)
SELECT [Id]
FROM [dbo].[Table]
WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()

它触发了这ReaderExecuting/ReaderExecuted对。

另一方面,如果实体没有数据库生成的身份,则可以直接插入实体而无需后续SELECT语句。在这种情况下,该NonQueryExecuting/NonQueryExecuted对被触发。(正如我自己测试的那样)。

于 2014-03-19T23:17:44.293 回答