简体   繁体   中英

Can I access the entity in IDbCommandInterceptor in Entity Framework

When implementing IDbCommandInterceptor, I can get access to the SQL command that has been created for the command/query. Is it also possible to get access to the actual entity object that is being persisted/retrieved whilst in the implemented methods?

Here is some fantasy code to demonstrate what I would like to do:

public class WidgetInterceptor : IDbCommandInterceptor
{
    public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        var widget = interceptionContext.Entity as Widget;

        if(widget != null)
        {
            //Perform tasks on widget before it is saved...
        }
    }
}

In the case of a query, there is no one entity. The executed SQL command can return any number of rows which may result in materialized entities, or some kind of projection. You can access the DbContext or ObjectContext involved, and through its ChangeTracker see the state of the entities within it, but as far as I'm aware there's no direct way to correlate the particular command you are executing with any specific entities. Depending upon your context, the number, type, and state of the entities in the ChangeTracker may be enough to do what you are after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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