Created
October 5, 2022 17:37
-
-
Save carloswm85/14a6418743c871ec81aff4b1c02ac981 to your computer and use it in GitHub Desktop.
Saving multiple entities in one transaction using Entity Framework.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (TransactionScope scope = new TransactionScope()) | |
{ | |
// TODO: Working on saving transaction | |
// Step 1 | |
if (driver.id > 0) _unitOfWork.PersonRepository.Update(driver); else _unitOfWork.PersonRepository.Add(driver); | |
if (destination.id > 0) _unitOfWork.DestinationRepository.Update(destination); else _unitOfWork.DestinationRepository.Add(destination); | |
_unitOfWork.Save(); | |
// Step 2 | |
transportation.id_persona_transportista = driver.id; | |
transportation.id_destino = destination.id; | |
if (transportation.id > 0) _unitOfWork.TransportationRepository.Update(transportation); else _unitOfWork.TransportationRepository.Add(transportation); | |
_unitOfWork.Save(); | |
// Step 3 | |
if (manager.id > 0) _unitOfWork.PersonRepository.Update(manager); else _unitOfWork.PersonRepository.Add(manager); | |
_unitOfWork.Save(); | |
// Step 4 | |
tracker.id_persona_encargado = manager.id; | |
tracker.id_transporte = transportation.id; | |
tracker.fecha_expedicion = DateTime.Now; | |
tracker.tiempo_expedicion = DateTime.Now.TimeOfDay; | |
_unitOfWork.TrackerRepository.Update(tracker); | |
_unitOfWork.Save(); | |
// Step 5 | |
scope.Complete(); // If we get here things are looking good. | |
_unitOfWork.Save(); // If we get here it is save to accept all changes. | |
} | |
// Rolls back the transaction. Entity not committed. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment