c# - EF 预编译 View 和自定义查询

标签 c# performance entity-framework ef-code-first query-performance

我正在尝试增加我的 EF 查询的“首次调用”执行时间,并发现可以使用查询的预编译 View 。在我使用名为“EF Code First Pre-generated views generator for C#”的 VS gallery 中的 T4 模板生成预编译 View 后,我没有注意到我的一些繁重查询(使用 Includes 和 Joins)有任何性能提升。

然后我尝试调查由 t4 模板生成的代码。我看到那里有一个从 DbMappingViewCache 派生的类,它通过其方法 GetView(EntitySetBase extent) 返回请求的 DbMappingView

看起来所有这些 View 都只用于简单查询,所以我问自己是否有任何方法可以在预编译阶段为我的特定重查询缓存 View 。有谁知道如何实现这一目标?有可能吗?

最佳答案

看看这个博客post其中谈到了几种减少启动时间的方法。

供引用:

  • 使用缓存数据库模型存储

    This has probabily the biggest impact on startup performance and is only necessary if you are using the code first model. Building and compiling large models using the Code First pipeline is extremly expensive in terms of start up time. This step will cache the code-first pipeline with its expensive o-c mapping generation and will store it in a xml file on the filesystem. The next time your application starts, EF will deserialize this cached mapping file which significantly reduces startup time.

  • 生成预编译 View :

    您已经这样做了,但也可以看看 Interactive Pre Generated Views for Entity Framework 6这让您可以预编译 View 并缓存它们,而不会因为增加构建时间而陷入困境。

  • 使用 n-gen 生成 entityframework 的预编译版本以避免 jitting

    Entity Framework does not come in the default installation of the .net Framework. Therefore, the EF assembly is not NGEN'd by default which means that EF code needs to be JITTED each time the application starts. Since EF is a really large and complex framework (EntityFramework assembly has over 5MB), and most of the code paths are needed even for simple scenarios, JITTING has a noticeable impact on startup performance.

    Running NGEN against EF is as simple as executing the following command within a root terminal session:

    %WINDIR%\Microsoft.NET\Framework\v4.0.30319\ngen install EntityFramework.dll
    

虽然与 EF 没有特别相关,但这里有一个技巧应该适用于一般的任何查询。我们的想法是通过 Application Initialization Module 预热您的应用程序.因此,将此添加到您的 web.config 中将导致此模块向 /startup 路由发送请求以执行初始化。

<applicationInitialization
     doAppInitAfterRestart="true" >
   <add initializationPage="/startup" />
</applicationInitialization>

使用此 View (/startup),您可以为测试用户触发繁重的查询(假设它是只读的),这将导致 EF 执行所有启动初始化。

查看此 answer了解让您的应用程序池始终运行的其他技巧。

关于c# - EF 预编译 View 和自定义查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22836373/

相关文章:

c# - 预期事件序列报告重复事件的测试助手

java - 如何在没有特定顺序的情况下管理多个可调用线程结果?

entity-framework - 清除 EntityCollection 然后在同一事务中添加到它似乎是不可能的

c# - 无法将对象添加到 context.DbSet。保存更改不起作用

c# - 从 session 0(服务)启动提升的用户进程

c# - LINQ to XML - 更新节点并将其保存到 XML 文件

c - 为什么 Linux 内核使用它所使用的数据结构?

entity-framework - EF DbContext。如何避免缓存?

c# - asp net core 1 RC2 AccountController注入(inject)

javascript - 为什么这段 JavaScript 代码经过 Node.js 优化后运行速度变慢了