Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework DbContext and thread safety

I need to update a few tables in my DB in a single transaction and I read that using DbContext.SaveChanges should be the way to do so.

However I also read that the lifetime of the DbContext should be as short as possible because it grows over time as it loads more entities.

Also I read that in order to make it thread-safe, each action should have its own DbContext.

Should I have a DbContext for each table I want to change and call SaveChanges on each DbContext? Wouldn't the last SaveChanges call override the changes of the previous calls?

What is the best way to do it? (I need this for a website)

like image 916
Idov Avatar asked Sep 05 '15 08:09

Idov


1 Answers

Entity Framework is not thread-safe. An MVC controller is instantiated per request. Thus if you use one DbContext per request, you're safe as long as you don't manually spawn threads in your controller actions (which you shouldn't do anyway).

Now if you have concurrency in your application, like a reservation system where multiple users are out to access the same scarce resources that can run out (like tickets), you'll have to implement logic around that yourself. No thread safety is going to help you there anyway.

That's why you're being asked for code in comments, because explaining thread safety in general is way too broad, and probably not applicable to your situation.

like image 112
CodeCaster Avatar answered Oct 22 '22 22:10

CodeCaster