示例#1
0
        public async Task <bool> AddField(AddFieldRequest request)
        {
            try
            {
                var fieldModel = _mapper.Map <FieldModel>(request.FieldRequest);
                fieldModel.CreatedDate = DateTime.Now;
                fieldModel.UpdatedDate = DateTime.Now;

                var disCountModel = _mapper.Map <DiscountModel>(request.DiscountRequest);
                disCountModel.CreatedDate = DateTime.Now;
                disCountModel.UpdatedDate = DateTime.Now;

                var pictureFields = _mapper.Map <IEnumerable <ImageFieldModel> >(request.PictureFieldRequest);

                // open begn transaction when we must insert foreign key to other tables
                await _repositoryWrapper.BeginTransactionAsync();

                // get return model to assign field id to other tables
                var fieldAfterSaved = await _repositoryWrapper.Field.CreateAsync(fieldModel);

                // Save to get Id Field then assign to discountModel and PictureFieldModel
                await _repositoryWrapper.SaveAsync();

                // assing id field before save
                disCountModel.FieldId = fieldAfterSaved.Id;
                await _repositoryWrapper.Discount.CreateAsync(disCountModel);

                // assing id field before save
                foreach (var item in pictureFields)
                {
                    item.FieldId     = fieldAfterSaved.Id;
                    item.CreatedDate = DateTime.Now;
                    item.UpdatedDate = DateTime.Now;
                }

                await _repositoryWrapper.PictureField.CreateRangeAsync(pictureFields);

                await _repositoryWrapper.SaveAsync();

                // comfirm Transaction
                await _repositoryWrapper.CommitAsync();

                return(true);
            }
            catch (Exception ex)
            {
                await _repositoryWrapper.RollbackAsync();

                throw ex;
            }
            finally
            {
                _repositoryWrapper.Dispose();
            }
        }