Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework's DbContext Lifetime in Worker Role

I have worker role that does some work with the database every second.

Is it ok to initialize the DbContext when the worker is started and use it throughout the lifetime of the worker?

How is the db connection handled? What if the database goes offline and back online? Will I still be able to use the context?

like image 863
daramasala Avatar asked Sep 30 '22 02:09

daramasala


1 Answers

My advice is to create, use and destroy the context for each operation... do not hang onto it. I used to worry at first because I had no idea how expensive it was to create the DbContext, the answer is, not very.

If you attempt to keep reusing a DbContext instance you will also run into problems (very quickly) as it's internal state models will start reporting conflicts for versions of the object that have been loaded (updated whatever) previously

like image 59
Paul Carroll Avatar answered Oct 07 '22 21:10

Paul Carroll