1

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;
Chris
  • 45
  • 9
  • Entity framework tracks changes in memory(by default). [Tracking vs No-tracking](https://learn.microsoft.com/en-us/ef/core/querying/tracking). Try adding `.AsNoTracking()`, like: `_context.Users.Where(...).AsNoTracking().FirstOrDefault()`. You can also disable tracking entirely in context-level (instead of repeating `.AsNoTracking()` everywhere. Check [this](https://stackoverflow.com/questions/12726878/global-setting-for-asnotracking) – Ergis Oct 31 '22 at 16:52
  • 3
    EF has ChangeTracker and it loaded the object from memory (it is not really caching). You can call ChangeTracker.Clear and the behavior that confuses you will go away :) – Nikita Chayka Oct 31 '22 at 16:52
  • @NikitaChayka I added this to my RollbackTransaction method and it now works as expected! – Chris Oct 31 '22 at 17:00

0 Answers0