实体框架的6个'ObjectQuery.EnablePlanCaching` - 它在哪里?

时间:2016-06-30 13:45:22

标签: entity-framework entity-framework-6

This article说明可以通过在EnablePlanCaching上将false设置为ObjectQuery来停用查询计划缓存,并且在EF6中默认启用它。

唉,EF6没有ObjectQueryDbSet给你DbQuery

我认为我不能从ObjectQuery获得DbQuery,我当然不想使用旧的ObjectContext。那么它是否有办法在EF6中禁用计划缓存?

1 个答案:

答案 0 :(得分:1)

这是一个扩展方法,可以让你从DbSet获取ObjectQuery

using (var ctx = new TestContext())
{
    var query = ctx.Products;
    query.GetObjectQuery().EnablePlanCaching = false;
    var list = query.ToList();
}


namespace Z.EntityFramework.Plus
{
    internal static partial class InternalExtensions
    {
        /// <summary>An IQueryable&lt;TEntity&gt; extension method that get the ObjectQuery from the query.</summary>
        /// <typeparam name="T">The type of elements of the query.</typeparam>
        /// <param name="query">The query to get the ObjectQuery from.</param>
        /// <returns>The ObjectQuery from the query.</returns>
        internal static ObjectQuery<T> GetObjectQuery<T>(this IQueryable<T> query)
        {
            // CHECK for ObjectQuery
            var objectQuery = query as ObjectQuery<T>;
            if (objectQuery != null)
            {
                return objectQuery;
            }

            // CHECK for DbQuery
            var dbQuery = query as DbQuery<T>;

            if (dbQuery == null)
            {
                throw new Exception("Oops! A general error has occurred. Please report the issue including the stack trace to our support team: info@zzzprojects.com");
            }

            var internalQueryProperty = dbQuery.GetType().GetProperty("InternalQuery", BindingFlags.NonPublic | BindingFlags.Instance);
            var internalQuery = internalQueryProperty.GetValue(dbQuery, null);
            var objectQueryContextProperty = internalQuery.GetType().GetProperty("ObjectQuery", BindingFlags.Public | BindingFlags.Instance);
            var objectQueryContext = objectQueryContextProperty.GetValue(internalQuery, null);

            objectQuery = objectQueryContext as ObjectQuery<T>;

            return objectQuery;
        }
    }
}