简体   繁体   English

实体框架6生成模型性能

[英]Entity Framework 6 generating model performance

I have an issue with EF6 on a web development. 我在网络开发中遇到EF6问题。 In the index page I need to execute a query to display some info, the problem is that the first query creates the model on memory and takes over 10 secs to do it (is not in a great hosting). 在索引页面中,我需要执行一个查询以显示一些信息,问题是第一个查询在内存上创建了模型,并花费了10秒钟以上的时间来完成(不在大型托管中)。 How people deal with this? 人们如何应对? Get first data with a direct query? 通过直接查询获取第一笔数据? read a txt file? 读取txt文件?

By default in EF it has a snapshot change tracking mechanism. 默认情况下,在EF中,它具有快照更改跟踪机制。

It works by saving entity states each time when it is loaded from the database. 它通过每次从数据库加载实体状态时保存实体状态来工作。 When for example SaveChanges method is called, Entity Framework checks all entities in current context and compares them with saved state. 例如,当调用SaveChanges方法时,实体框架将检查当前上下文中的所有实体,并将它们与保存状态进行比较。

This can be a touch slow sometimes... in the context ctor chuck this in: 有时候这可能会有点慢...在上下文中,ctor会这样:

this.Configuration.AutoDetectChangesEnabled = false;

this turns off entity tracking which should take away a bit of the overhead here. 这会关闭实体跟踪,这会减少此处的一些开销。

However, if it is fairly static data, perhaps you can use a cache to hold on to the data when the app starts up then you only need to pull it from memory and have it refresh every x hours/minutes. 但是,如果它是相当静态的数据,也许您可​​以在应用程序启动时使用缓存来保留数据,那么您只需要将其从内存中拉出并每隔x小时/分钟刷新一次即可。

Also, as an aside, move to AZURE if you can, it won't cost much more I expect and will be a lot easier to work with for deployments etc. 此外,顺便说一句,如果可以的话,转到AZURE,它不会花费我期望的更多,并且在部署等方面使用起来会容易得多。

There are two things I'd do: 1) Profile your query and see if it really needs to take 10 seconds. 我要做两件事:1)分析您的查询,看看它是否真的需要10秒。 Check out LINQPad, Glimpse, or Stackify prefix for ways to view the SQL query that is generated from EF. 请查看LINQPad,Glimpse或Stackify前缀,以查看查看从EF生成的SQL查询的方法。 An inefficient query might be your problem. 查询效率低下可能是您的问题。 Using a view in your DB or setting indexes may fix the problem. 在数据库中使用视图或设置索引可能会解决此问题。

2) If you want to run this query once and then use an in-memory copy for subsequent requests, use MemoryCache . 2)如果要运行一次此查询,然后对后续请求使用内存中的副本,请使用MemoryCache There will still be a performance hit for the first request, but all subsequent requests will be incredibly fast for as long as the cache is set to last. 第一个请求仍然会影响性能,但是只要将缓存设置为最后一个,所有后续请求的速度都会非常快。 There is a memory hit when using this because you're keeping the results in memory long-term. 使用此功能时会导致内存不足,因为您会将结果长期保存在内存中。 If every visitor has a dynamic request on the index page, you will use a lot of memory. 如果每个访问者在索引页面上都有一个动态请求,则将占用大量内存。 If the request is the same for all users, this will be a great option. 如果所有用户的请求都相同,这将是一个不错的选择。

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

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