public async Task <int> AddPostAccessLog(int postId, int userId = 0)
        {
            var affected = 0;

            //transaction = dbContext.Database.BeginTransaction();

            dbContext.PostAccessLogs.Add(new PostAccessLog
            {
                PostId    = postId,
                CreatedAt = DateTimeOffset.UtcNow,
                IpAddress = GetRemoteIpAddress(),
                UserAgent = GetUserAgent(),
                UserId    = userId > 0 ? userId : (int?)null
            });

            try
            {
                affected = await dbContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);

                if (transaction != null)
                {
                    transaction.Rollback();
                    transaction.Dispose();
                }

                transaction = null;
            }

            return(affected);
        }
Ejemplo n.º 2
0
        public void Dispose()
        {
            if (transaction == null)
            {
                return;
            }

            transaction.Dispose();
        }
Ejemplo n.º 3
0
 public void PlaceOrder(Models.Order order)
 {
     Entities.StoreOrder o = new Entities.StoreOrder();
     if (order.Location.LocationID != null)
     {
         o.LocationId = (int)order.Location.LocationID;
     }
     if (order.Customer.CustomerID != null)
     {
         o.CustomerId = (int)order.Customer.CustomerID;
     }
     o.CheckedOut = DateTime.Now;
     ctx.StoreOrders.Add(o);
     foreach (Models.Item i in order.Items)
     {
         Entities.OrderItem oi = new Entities.OrderItem();
         if (i.Product.ProductID != null)
         {
             oi.ProductId = (int)i.Product.ProductID;
         }
         oi.Quantity = i.Quantity;
         o.OrderItems.Add(oi);
     }
     ctx.SaveChanges();
     try {
         transaction.Commit();
         using var log = new LoggerConfiguration()
                         .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, shared: true)
                         .CreateLogger();
         log.Information("TRANSACTION: Committed");
         transaction.Dispose();
         transaction = ctx.Database.BeginTransaction();
     } catch (Exception e) {
         Console.WriteLine(e.StackTrace);
         using var log = new LoggerConfiguration()
                         .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, shared: true)
                         .CreateLogger();
         log.Information("TRANSACTION: Rolled back due to database throwing exception");
         transaction.Rollback();
     }
 }
        /// <summary>
        /// Persists all updates to the data source and resets change tracking in the object context.
        /// </summary>
        /// <returns>The number of objects in an System.Data.Entity.EntityState.Added, System.Data.Entity.EntityState.Modified, or System.Data.Entity.EntityState.Deleted state when System.Data.Objects.ObjectContext.SaveChanges() was called.</returns>
        public override int SaveChanges()
        {
            var cancel = false;

            OnBeforeSaveChanges(ref cancel);
            if (cancel)
            {
                return(0);
            }

            var markedTime = System.DateTime.Now;

            //Get the added list
            var addedList = this.ChangeTracker.Entries().Where(x => x.State == EntityState.Added);

            //Process added list
            foreach (var item in addedList)
            {
                var entity = item.Entity as IAuditable;
                if (entity != null)
                {
                    var audit = entity as IAuditableSet;
                    if (entity.IsModifyAuditImplemented && entity.ModifiedBy != this.ContextStartup.Modifier)
                    {
                        if (audit != null)
                        {
                            audit.CreatedBy = this.ContextStartup.Modifier;
                        }
                        if (audit != null)
                        {
                            audit.ModifiedBy = this.ContextStartup.Modifier;
                        }
                    }
                    audit.CreatedDate  = markedTime;
                    audit.ModifiedDate = markedTime;
                }
            }
            this.OnBeforeSaveAddedEntity(new EventArguments.EntityListEventArgs {
                List = addedList
            });

            //Process modified list
            var modifiedList = this.ChangeTracker.Entries().Where(x => x.State == EntityState.Modified);

            foreach (var item in modifiedList)
            {
                var entity = item.Entity as IAuditable;
                if (entity != null)
                {
                    var audit = entity as IAuditableSet;
                    if (entity.IsModifyAuditImplemented && entity.ModifiedBy != this.ContextStartup.Modifier)
                    {
                        if (audit != null)
                        {
                            audit.ModifiedBy = this.ContextStartup.Modifier;
                        }
                    }
                    audit.ModifiedDate = markedTime;
                }
            }
            this.OnBeforeSaveModifiedEntity(new EventArguments.EntityListEventArgs {
                List = modifiedList
            });

            var retval = 0;

            Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction customTrans = null;
            try
            {
                _paramList.Clear();
                if (base.Database.CurrentTransaction == null)
                {
                    customTrans = base.Database.BeginTransaction();
                }
                retval += base.SaveChanges();
                if (customTrans != null)
                {
                    customTrans.Commit();
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (customTrans != null)
                {
                    customTrans.Dispose();
                }
            }
            this.OnAfterSaveAddedEntity(new EventArguments.EntityListEventArgs {
                List = addedList
            });
            this.OnAfterSaveModifiedEntity(new EventArguments.EntityListEventArgs {
                List = modifiedList
            });
            OnAfterSaveChanges();
            return(retval);
        }