EF6 Disable Query Plan Caching with Command Tree Interceptor

后端 未结 4 1966
执笔经年
执笔经年 2021-02-18 14:28

I\'m using IDbCommandTreeInterceptor to implement soft-delete functionality. Inside standard TreeCreated method I check whether given query command con

4条回答
  •  长发绾君心
    2021-02-18 14:42

    It's important to distinguish between Query Plan Caching and Result Caching:

    Caching in the Entity Framework

    Query Plan Caching

    The first time a query is executed, it goes through the internal plan compiler to translate the conceptual query into the store command (e.g. the T-SQL which is executed when run against SQL Server). If query plan caching is enabled, the next time the query is executed the store command is retrieved directly from the query plan cache for execution, bypassing the plan compiler.

    The query plan cache is shared across ObjectContext instances within the same AppDomain. You don't need to hold onto an ObjectContext instance to benefit from query plan caching.

    A Query Cache is an optimized SQL instruction plan. These plans help make EF queries faster than "Cold" Queries. These Plans are cached beyond and particular context.

    Object caching:

    By default when an entity is returned in the results of a query, just before EF materializes it, the ObjectContext will check if an entity with the same key has already been loaded into its ObjectStateManager. If an entity with the same keys is already present EF will include it in the results of the query. Although EF will still issue the query against the database, this behavior can bypass much of the cost of materializing the entity multiple times.

    In other words, Object Caching is a soft form of Results Caching. No other kind 2nd Level Cache is available with Entity Framework unless you specifically include it. Second-Level Caching in the Entity Framework and Azure

    AsNoTracking

    Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext

    Context.Set().AsNoTracking();
    

    Or you can disable object caching for an entity using MergeOption NoTracking Option:

    Will not modify cache.

    context.Objects.MergeOption = MergeOption.NoTracking; 
    var retrievedObj= context.Objects.Find(obj.Id);
    

    As opposed to the AppendOnly Option

    Will only append new (top level-unique) rows. This is the default behavior.

    this is the default behavior you have been struggling with

提交回复
热议问题