❔ What’s the point of Database.BeginTransaction?
I’m trying to wrap my head around it, what is the main reason for using BeginTransaction?
Is it because we want to make sure that both Save transactions are done successful before Commit or is because you have to make sure Disposing will rollback the first transaction i.e. out of two transaction?
I find Disposing not Rollingback in time my transaction if I refresh the page.
The class that has the logic of transactions should be Disposable also or just using a “using” block is enough?
Thank you!
4 Replies
Let's say you have a code flow that relies on you to save something inside of your DbContext. For example, you have to create a person. You save this person to get an ID and then do an external API call. You take information from that external API call that tells you something crucial about this person that you wish to save, but you cannot do it for any reason whatsoever. Perhaps the API failed or your database table does not allow it. Without a transaction, you have a half saved person in your database now. With a transaction, you can just rollback your first SaveChanges.
Great example, thank you! What happens if the user closes or refreshes the browser in between? Before Commit is hit. My class in Disposable (Accesor.cs) but the dispose method is not hit or is hit very later, after 5 mins. All this time the changes are not yet rolledback? Should I always use a “using block”?
It depends on your situation. The garbage collector will clean up any resources the moment their scope is no longer used. With a using block you are making that scope smaller.
Look at it like this
If you had to run SaveChanges to get some data that another part of your code relies on, you don't want that data to remain if the other part failed.
I do not know what your use case is, but usually you do not let your user interact with things in the middle of a transaction.
You'd use it in an async method so that the user can go about their business whilst this code finishes up in the background.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.