Can I access the entity in IDbCommandInterceptor in Entity Framework

独自空忆成欢 提交于 2019-12-06 05:29:59

问题


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...
        }
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/20420067/can-i-access-the-entity-in-idbcommandinterceptor-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!