0
\$\begingroup\$

I am using asp.net web API and EF code first. I am querying the database based on values inside of the request object (initiate). If there are results, I am updating the database. Then I am querying this updated results in the database and save it to another table (initiateResponse).

This is a very fat controller, it needs to be refactored. I read some articles and decided to use repository pattern and unit of work for transactions. I need your help to refactor this controller portion. Any suggestions?

Should I need TransactionScope or UOW handles it?


            //Check Games in our database - all or nothing
            var gameBankResult = await (context.GameBanks.Where(g => g.productCode == initiate.productCode)
                .Where(l => l.referenceId == null)
                ).ToListAsync();
            //If we have exact number of games in our database, mark them!
            if (gameBankResult.Count() != 0 && gameBankResult.Count() >= initiate.quantity)
            {
                for (var index = 0; index < initiate.quantity; index++)
                {
                    var item = gameBankResult[index];
                    item.referenceId = initiate.referenceId;
                    context.Entry(item).State = System.Data.Entity.EntityState.Modified;
                }


                //Update marked games
                await context.SaveChangesAsync();

                //Return marked games from database
                var gameBankResultVM = await (context.GameBanks.Where(g => g.productCode == initiate.productCode)
                    .Where(l => l.referenceId == initiate.referenceId)
                    .Take(initiate.quantity)
                    .Select(g => new GameBankInitiationResponseVM()
                    {
                        referenceId = g.referenceId,
                        productCode = g.productCode,
                        quantity = initiate.quantity,
                        initiationResultCode = g.initiationResultCode,
                        validatedToken = g.validatedToken,
                        currency = g.currency,
                        estimateUnitPrice = g.estimateUnitPrice,
                        version = g.version,
                        signature = g.signature,
                        ApplicationCode = g.ApplicationCode,
                        companyToken = token,
                    })).ToListAsync();


                var resultObj = gameBankResultVM[0];

                var initiateResponse = JsonConvert.SerializeObject(resultObj);
                var responseDB = JsonConvert.DeserializeObject<InitiateResponse>(initiateResponse);
                //Adding Response into database
                context.InitiateResponses.Add(responseDB);
                await context.SaveChangesAsync();
                return Ok(resultObj);

            }


I implemented an interface as follows:

public interface IApiController<TDto, T>
    {
        #region GetMethods
        Task<ApiResult<TDto>> FindAsync(TDto item);
        #endregion

        #region PostMethods
        ApiResult<TDto> Add(TDto item);
        Task<ApiResult<TDto>> AddAsync(TDto item);
        ApiResult<TDto> Update(TDto item);
        Task<ApiResult<TDto>> UpdateAsync(TDto item);

        #endregion
    }

Here is my reposirtory:

public class GenericRepository<T> : IGenericRepository<T> where T : class
    {
        #region Variables

        private DbContext _context;
        private DbSet<T> _dbset;
        #endregion

        #region Constructor

        public GenericRepository(DbContext context)
        {

            _context = context;
            _dbset = _context.Set<T>();
        }
        #endregion

        #region GetterMethods

        public IQueryable<T> GetAll()
        {
            return _dbset;
        }


        public T Find(Guid Id)
        {
            return _dbset.Find(Id);
        }
        #endregion

        #region SetterMethods

        public T Update(T entityToUpdate)
        {
            _dbset.Attach(entityToUpdate);
            _context.Entry(entityToUpdate).State = EntityState.Modified;
            return entityToUpdate;
        }


        public T Add(T entity)
        {
            _dbset.Add(entity);
            return entity;
        }



        #endregion

    }

Here is my UOW:

public class UnitofWork : IUnitofWork
    {
        #region Variables

        private readonly DbContext _context;
        private DbContextTransaction _transaction;
        private bool _disposed;
        #endregion

        #region Constructor

        public UnitofWork(DbContext context)
        {
            _context = context;
        }
        #endregion

        #region BusinessSection

        public IGenericRepository<T> GetRepository<T>() where T : class
        {
            return new GenericRepository<T>(_context);
        }


        public bool BeginNewTransaction()
        {
            try
            {
                _transaction = _context.Database.BeginTransaction();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


        public bool RollBackTransaction()
        {
            try
            {
                _transaction.Rollback();
                _transaction = null;
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


        public int SaveChanges()
        {
            var transaction = _transaction ?? _context.Database.BeginTransaction();
            using (transaction)
            {
                try
                {

                    if (_context == null)
                    {
                        throw new ArgumentException("Context is null");
                    }

                    int result = _context.SaveChanges();


                    transaction.Commit();
                    return result;
                }
                catch (Exception ex)
                {

                    transaction.Rollback();
                    throw new Exception("Error on save changes ", ex);
                }
            }
        }
        #endregion

        #region DisposingSection

        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this._disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

    }

```
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.