Question

I am using EF 6 and attempting to use the IDbCommandInterceptor from the System.Data.Entity.Infrastructure.Interception namespace.

It works well for reading, and updating, however when I add a new entity to the database, the NonQueryExecuted() does not fire, nor does the NonQueryExecuting(). Is this normal behavior by the Interceptor or is something not being implemented correctly on my end?

Code:

Interceptor:

    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)
        {
        }

DataContextBase:

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

La solution

This is by design. When an entity with a database-generated identity is inserted, an insert statement is accompanied by a SELECT statement to read the generated identity value into the Id property of the inserted entity. The command has this shape:

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

It triggers the ReaderExecuting/ReaderExecuted pair.

If, on the other hand, an entity hasn't got a database-generated identity, the entity can just be inserted without a subsequent SELECT statement. In this case the NonQueryExecuting/NonQueryExecuted pair is triggered. (As I tested myself).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top