Entity Framework ObjectContext re-usage

后端 未结 6 585
我寻月下人不归
我寻月下人不归 2020-12-24 15:45

I\'m learning EF now and have a question regarding the ObjectContext:

Should I create instance of ObjectContext for every query (function) when I access the database

6条回答
  •  无人及你
    2020-12-24 16:09

    Definitely for every query. It's a lightweight object so there's not much cost incurred creating one each time you need it.

    Besides, the longer you keep an ObjectContext alive, the more cached objects it will contain as you run queries against it. This may cause memory problems. Therefore, having the ObjectContext as a singleton is a particularly bad idea. As your application is being used you load more and more entities in the singleton ObjectContext until finally you have the entire database in memory (unless you detach entities when you no longer need them).

    And then there's a maintainability issue. One day you try to track down a bug but can't figure out where the data was loaded that caused it.

提交回复
热议问题