Entity Framework + Multiple Threads + Lazy Load

喜夏-厌秋 提交于 2019-12-18 07:44:37

问题


I'm having issues with Entity Framework and multiple threads and I am wondering if there is a solution that keeps the ability to lazy load. From my understanding the data context is not thread safe which is why when I have multiple threads using the same data context I get various data readers error. The solution to this problem is to use a separate data context for each connection to the database and then destroy the data context. Unfortunately destroying my data context then prevents me from doing lazy loading.

Is there a pattern to allow me to have a shared context across my application, but still properly handle multiple threads?


回答1:


No, there is no such solution. Your choices in multithreaded application are:

  • Context per thread
  • Single context producing unproxied detached entities (no lazy loading, no change tracking) with synchronization for each access to that context.

Doing the second approach with proxied attached entities is way to disaster. It would require to detect all hidden interactions with the context and make related code also synchronized. You will probably end with single threaded process running in multiple switching threads.



来源:https://stackoverflow.com/questions/7176303/entity-framework-multiple-threads-lazy-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!