简体   繁体   English

我可以在Entity Framework中的IDbCommandInterceptor中访问实体吗?

[英]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. 实现IDbCommandInterceptor时,我可以访问为命令/查询创建的SQL命令。 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. 执行的SQL命令可以返回任意数量的行,这些行可能导致实体化实体或某种投影。 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. 您可以访问所涉及的DbContext或ObjectContext,并通过其ChangeTracker查看其中的实体状态,但据我所知,没有直接的方法将您正在执行的特定命令与任何特定实体相关联。 Depending upon your context, the number, type, and state of the entities in the ChangeTracker may be enough to do what you are after. 根据您的上下文,ChangeTracker中实体的数量,类型和状态可能足以完成您的工作。

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

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