Persist Entity Framework query cache

2019-02-07 08:02发布

I have an ASP.NET MVC 5 web-application and use EF 6.1 to access my DB.
I have some rather complex LINQ queries which take up to 10s to compile, but then execute in a few milliseconds. EF does cache this queries fine and the second time the query is executed it returns within this few milliseconds.
But this cache is not persisted so on every app-restart the query needs to be recompiled, which takes that 10s again.

Is there a way to persist this query cache so it survives an app-restart?

1条回答
放荡不羁爱自由
2楼-- · 2019-02-07 08:49

You can use compiled queries: see here or here

static readonly Func<AdventureWorksEntities, Decimal, IQueryable<SalesOrderHeader>> s_compiledQuery2 = 
CompiledQuery.Compile<AdventureWorksEntities, Decimal, IQueryable<SalesOrderHeader>>(
        (ctx, total) => from order in ctx.SalesOrderHeaders
                        where order.TotalDue >= total
                        select order);

But as mentioned here the query object must not go out of scope. You can handle this by either keeping it cached in the session or as application variable.

查看更多
登录 后发表回答