I am trying to implement the Unit of Work pattern and have hit an unexpected behavior. My controller below successfully gets the user from the db, updates the name, and rolls back the transaction. After running this method, no change is made to the db as expected. However, the db query after the rollback still gets the user with the changed name and I don't understand why. Does EF perform some kind of caching?
public ActionResult GetTest()
{
_unitOfWork.BeginTransaction();
var user = _unitOfWork.UserRepository.GetByID(123);
// current name is "Chris"
user.Name = "Adam";
_unitOfWork.Save();
_unitOfWork.RollbackTransaction();
var user2 = _unitOfWork.LarRepository.GetByID(123);
// user2.Name is equal to "Adam" but the DB was never updated and I expected "Chris"
return Ok(user2) ;
}
Here are the applicable Unit of Work methods
public void Save()
{
_context.SaveChanges();
}
public void BeginTransaction()
{
_transaction = _context.Database.BeginTransaction();
}
public void CommitTransaction()
{
if (_transaction != null)
_transaction.Commit();
}
public void RollbackTransaction()
{
if (_transaction != null)
_transaction.Rollback();
}
private IDbContextTransaction _transaction;