Using transactions

A good database implementation will have the Atomicity, Consistency, Isolation, and Durability (ACID) properties.

Transactions are vital for maintaining data integrity in a database. They help ensure that data that's logically grouped together is treated as one item in a unit of operation. This goes a long way to ensure ACID properties are preserved.

When a unit of operation is triggered and saved to the database, all of the constituent logically grouped operations are successfully saved. This is what is called a transaction. If part of the transaction fails, then everything is rolled back. Transactions operate in an all-or-nothing scenario.

Microsoft SQL Server database is one of the many databases that actually support transactions. This means that, if we call the SaveChanges() method using Entity Framework Core, then every change gets treated as part of a transaction, so all the changes get saved – or none get saved in the case of an error.

You don't necessarily need to implement transactions in your own custom way, especially in most basic applications that you may be required to develop.

For most applications, this default behavior is sufficient. You should only manually control transactions if your application requirements deem it necessary. But if you are required to, you can place your processes into a transaction as follows:

using (var gameContext = new GameDbContext())
{
using (var gameTransaction =
gameContext.Database.BeginTransaction())
{
try
{
gameContext.GameInvitation.Add(new GameInvitation { ... });
gameContext.SaveChanges();

gameContext.GameSession.Add(new GameSession { ... });
gameContext.SaveChanges();

gameTransaction.Commit(); // Both the above
operations will be in this transaction
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message)
}
}
}

In the preceding code snippet, we instantiated a new game database context and started a transaction on it with two processes that added a game invitation and a game session. These are committed in one go, and if any of them fail individually, then none of them will be saved at all – it's all or nothing.

This is a good point to end our discussion of Entity Framework Core 3.0 for the purposes of this book, which mainly focuses on ASP.NET Core 3. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.168.211