Resolved Update problem

raysefo

Well-known member
Joined
Feb 22, 2019
Messages
361
Programming Experience
10+
Hi,

I am trying to update the table. But it does not. How come, I don't understand. There is no error either.

C#:
...
var gameBankResult =
                    await _unitOfWork.GameBankRepository.GetGamesAsync(g =>
                        g.productCode == requestDto.productCode && g.referenceId == Guid.Empty); --> returns 1 result

                //If we have exact number of games in our database, mark them!
                if (gameBankResult.Count() != 0 && gameBankResult.Count() >= requestDto.quantity)
                {
                    for (var index = 0; index < requestDto.quantity; index++)
                    {
                        var item = gameBankResult[index];
                        item.referenceId = gameRequest.referenceId;
                        item.requestDateTime = DateTime.Now;
                        item.responseDateTime = DateTime.Now;
                        _unitOfWork.GameBankRepository.Update(item);
                        await _unitOfWork.SaveAsync(); ---> does not update the table
                    }

                    //Query GameBank database
                    var gameBankConfirmResult =
                        await _unitOfWork.GameBankRepository.GetGamesAsync(g =>
                            g.referenceId == gameRequest.referenceId); ---> returns no result
                ...

Generic Repo:
C#:
public virtual void Update(TEntity entityToUpdate)
        {
            dbSet.Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }

Unit of work: :
C#:
public async Task SaveAsync()
        {
            await _context.SaveChangesAsync();
            
        }
 
If you set a breakpoint on UnitOfWork.SaveAsync(), does it even get called?
 
If you need help understanding the debugger and how to set break points, you can find a link in my signature for that.
 
If you set a breakpoint on UnitOfWork.SaveAsync(), does it even get called?

Yes, I found out that it is due to Transaction scope. If I don't use Transaction scope it updates immediately but this time how can I rollback if one of the insert/updates fails.

C#:
private async Task<HttpResponseMessage> CallGame(RequestDto requestDto)
        {
            
            HttpResponseMessage response = null;
            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                //Transform DTO into GameRequest for calling Game Initiate
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<RequestDto, GameRequest>();
                    cfg.CreateMap<GameRequest, GameConfirmRequest>();
                    cfg.CreateMap<GameBank, GameConfirmResponse>();
                    cfg.CreateMap<GameBankPin, Coupon>();
                    cfg.CreateMap<GameRequest, GameRequestDto>();
                });
                var iMapper = config.CreateMapper();
                var gameRequest = iMapper.Map<RequestDto, GameRequest>(requestDto);
                //Unique reference ID
                gameRequest.referenceId = Guid.NewGuid();

                var gameRequestDto = iMapper.Map<GameRequest, GameRequestDto>(gameRequest);
                //Create signature
                gameRequest = Utilities.CreateSignature(gameRequestDto, RequestType.Initiate);

                //Add initiation request into database
                _unitOfWork.GameRepository.Insert(gameRequest);

                //Query GameBank database
                var gameBankResult =
                    await _unitOfWork.GameBankRepository.GetGamesAsync(g =>
                        g.productCode == requestDto.productCode && g.referenceId == Guid.Empty);

                //If we have exact number of games in our database, mark them!
                if (gameBankResult.Count() != 0 && gameBankResult.Count() >= requestDto.quantity)
                {
                    for (var index = 0; index < requestDto.quantity; index++)
                    {
                        var item = gameBankResult[index];
                        item.referenceId = gameRequest.referenceId;
                        item.requestDateTime = DateTime.Now;
                        item.responseDateTime = DateTime.Now;
                        _unitOfWork.GameBankRepository.Update(item);
                        await _unitOfWork.SaveAsync();
                    }

                    //Query GameBank database
                    var gameBankConfirmResult =
                        await _unitOfWork.GameBankRepository.GetGamesAsync(g =>
                            g.referenceId == gameRequest.referenceId);
                    if (gameBankConfirmResult != null)
                    {
                        if (gameBankConfirmResult.Count == 1)
                        {
                            var gameBankConfirmResponse = iMapper.Map<IList<GameBank>, IList<GameConfirmResponse>>(gameBankConfirmResult);
                            gameBankConfirmResponse[0].purchaseStatusDate = DateTime.Now;
                            //Add confirm response into database
                            _unitOfWork.GameConfirmResponseRepository.Insert(gameBankConfirmResponse[0]);
                            var resultResponse = JsonConvert.SerializeObject(
                                gameBankConfirmResponse[0],Formatting.Indented,
                            new JsonSerializerSettings()
                            {
                                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                            });
                            response = new HttpResponseMessage
                            {
                                StatusCode = System.Net.HttpStatusCode.OK,
                                Content = new StringContent(
                                    resultResponse, System.Text.Encoding.UTF8,
                                    "application/json"),
                            };
                        }
                        else if(gameBankConfirmResult.Count > 1)
                        {
                            var gameResult = new GameConfirmResponse
                            {
                                coupons = new List<Coupon>()
                            };
                            var price = 0.0;
                            var quantity = 0;

                            foreach (var item in gameBankConfirmResult)
                            {
                                price = price + item.unitPrice;
                                quantity = quantity + 1;
                                foreach (var coupons in item.coupons)
                                {
                                    var gameCouponResult = new Coupon()
                                    {
                                        expiryDate = coupons.expiryDate,
                                        Pin = coupons.Pin,
                                        Serial = coupons.Serial
                                    };
                                    //Add coupon values
                                    gameResult.coupons.Add(gameCouponResult);
                                }

                            }

                            //Set summed/counted values
                            gameResult.referenceId = gameBankConfirmResult[0].referenceId;
                            gameResult.productCode = gameBankConfirmResult[0].productCode;
                            gameResult.quantity = quantity;
                            gameResult.currency = gameBankConfirmResult[0].currency;
                            gameResult.unitPrice = gameBankConfirmResult[0].unitPrice;
                            gameResult.totalPrice = price;
                            gameResult.productDescription = gameBankConfirmResult[0].productDescription;
                            gameResult.totalPayablePrice = price;

                            //var gameBankConfirmResponse = iMapper.Map<GameBank, GameConfirmResponse>(gameResult);
                            //Add confirm response into database
                            _unitOfWork.GameConfirmResponseRepository.Insert(gameResult);
                            var resultResponse = JsonConvert.SerializeObject(
                                gameResult, Formatting.Indented,
                                new JsonSerializerSettings()
                                {
                                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                });
                            response = new HttpResponseMessage
                            {
                                StatusCode = System.Net.HttpStatusCode.OK,
                                Content = new StringContent(
                                    resultResponse, System.Text.Encoding.UTF8,
                                    "application/json"),
                            };
                        }
                    }
                }

                await _unitOfWork.SaveAsync();

                scope.Complete();
            }

            return response;
        }
 
You can't have your cake and eat it too. If you need to be able to roll back then you need a transaction and anything that occurs inside that transaction will not be committed until the transaction is complete. What's the actual problem? Are you committing the transaction immediately afterwards anyway?
 
I guess I need to change the logic. Long story short, I am querying a table based on product code which has empty GUID.

C#:
/Query GameBank database
                var gameBankResult =
                    await _unitOfWork.GameBankRepository.GetGamesAsync(g =>
                        g.productCode == requestDto.productCode && g.referenceId == Guid.Empty);

If there are suitable records in the table, I am updating them. I am also setting manually generated referenceId here.

C#:
if (gameBankResult.Count() != 0 && gameBankResult.Count() >= requestDto.quantity)
                {
                    for (var index = 0; index < requestDto.quantity; index++)
                    {
                        var item = gameBankResult[index];
                        item.referenceId = gameRequest.referenceId;
                        item.requestDateTime = DateTime.Now;
                        item.responseDateTime = DateTime.Now;
                        _unitOfWork.GameBankRepository.Update(item);
                        await _unitOfWork.SaveAsync();
                    }

Then I again query this updated table for this specific referenceId and generate response message.

C#:
 var gameBankConfirmResult =
                        await _unitOfWork.GameBankRepository.GetGamesAsync(g =>
                            g.referenceId == gameRequest.referenceId);
                    if (gameBankConfirmResult != null)
                    {
                        if (gameBankConfirmResult.Count == 1)

I think the second query is not necessary. I should try to generate a response from the first query.
 
Back
Top Bottom