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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With