public void Save(E entity) { String entitySetName = eContainerName + "." + eClass.Name; ctx.AddObject(entitySetName, entity); ctx.SaveChanges(); ctx.Refresh(RefreshMode.StoreWins, entity); ctx.AcceptAllChanges(); }
/// <summary> /// Removes the transactions marked for deletion if their number exceeds <see cref="P:System.Data.Entity.Infrastructure.CommitFailureHandler.PruningLimit" />. /// </summary> /// <param name="force"> /// if set to <c>true</c> will remove all the old transactions even if their number does not exceed <see cref="P:System.Data.Entity.Infrastructure.CommitFailureHandler.PruningLimit" />. /// </param> /// <param name="useExecutionStrategy"> /// if set to <c>true</c> the operation will be executed using the associated execution strategy /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task that represents the asynchronous operation.</returns> protected virtual async Task PruneTransactionHistoryAsync( bool force, bool useExecutionStrategy, CancellationToken cancellationToken) { if (this._rowsToDelete.Count <= 0 || !force && this._rowsToDelete.Count <= this.PruningLimit) { return; } foreach (TransactionRow entity in this.TransactionContext.Transactions.ToList <TransactionRow>()) { if (this._rowsToDelete.Contains(entity)) { this.TransactionContext.Transactions.Remove(entity); } } ObjectContext objectContext = ((IObjectContextAdapter)this.TransactionContext).ObjectContext; try { int num = await((IObjectContextAdapter)this.TransactionContext).ObjectContext.SaveChangesInternalAsync(SaveOptions.None, !useExecutionStrategy, cancellationToken).WithCurrentCulture <int>(); this._rowsToDelete.Clear(); } finally { objectContext.AcceptAllChanges(); } }
/// <summary> /// Removes the transactions marked for deletion if their number exceeds <see cref="P:System.Data.Entity.Infrastructure.CommitFailureHandler.PruningLimit" />. /// </summary> /// <param name="force"> /// if set to <c>true</c> will remove all the old transactions even if their number does not exceed <see cref="P:System.Data.Entity.Infrastructure.CommitFailureHandler.PruningLimit" />. /// </param> /// <param name="useExecutionStrategy"> /// if set to <c>true</c> the operation will be executed using the associated execution strategy /// </param> protected virtual void PruneTransactionHistory(bool force, bool useExecutionStrategy) { if (this._rowsToDelete.Count <= 0 || !force && this._rowsToDelete.Count <= this.PruningLimit) { return; } foreach (TransactionRow entity in this.TransactionContext.Transactions.ToList <TransactionRow>()) { if (this._rowsToDelete.Contains(entity)) { this.TransactionContext.Transactions.Remove(entity); } } ObjectContext objectContext = ((IObjectContextAdapter)this.TransactionContext).ObjectContext; try { objectContext.SaveChangesInternal(SaveOptions.None, !useExecutionStrategy); this._rowsToDelete.Clear(); } finally { objectContext.AcceptAllChanges(); } }
public static void ApplyDetachedPropertyChanges <T>(this ObjectContext db, T entity, Func <T, int> getIdDelegate) where T : EntityObject { var entitySetName = db.DefaultContainerName + "." + entity.GetType().Name; var id = getIdDelegate(entity); var entityKey = new EntityKey(entitySetName, "Id", id); db.Attach(new Department { Id = id, EntityKey = entityKey }); db.AcceptAllChanges(); db.ApplyPropertyChanges(entitySetName, entity); }
public static void AddObjectsAndSaveWithIdentityInsert <T>( this ObjectContext context, IEnumerable <T> objects) where T : EntityObject { if (!objects.Any()) { return; } Action <IEnumerable <T> > exec = (obj) => { var policy = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy> (10, TimeSpan.FromSeconds(10)); var name = context.GetTableName <T>(); foreach (var item in obj) { context.AddObject(name, item); } policy.ExecuteAction(() => { context.Connection.Open(); var trans = context.Connection.BeginTransaction(); context.ExecuteStoreCommand("SET IDENTITY_INSERT " + context.GetTableName <T>() + " ON"); context.SaveChanges(); context.ExecuteStoreCommand("SET IDENTITY_INSERT " + context.GetTableName <T>() + " OFF"); trans.Commit(); context.AcceptAllChanges(); context.Connection.Close(); }); }; context.AddObjectsAndSave(objects, doThisInstead: exec); }
public async Task <int> PrivateSaveChangesAsync(CancellationToken cancellationToken) { // If you want to have audits in transaction with records you must handle // transactions manually using (var scope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)) { ObjectContext context = ((IObjectContextAdapter)this).ObjectContext; await context.SaveChangesAsync(SaveOptions.DetectChangesBeforeSave, cancellationToken).ConfigureAwait(false); // Now you must call your audit code but instead of adding audits to context // you must add them to list. var audits = new List <Audit>(); var currentUser = "******"; foreach (var entry in ChangeTracker.Entries().Where(o => o.State != EntityState.Unchanged && o.State != EntityState.Detached).ToList()) { var changeType = entry.State.ToString(); Type entityType = GetEntityType(entry); string tableName = GetTableName(context, entityType); string identityJson = GetIdentityJson(entry, entityType); var audit = new Audit { Id = Guid.NewGuid(), ChangeType = changeType, ObjectType = entityType.ToString(), FromJson = (entry.State == EntityState.Added ? "{ }" : GetAsJson(entry.OriginalValues)), ToJson = (entry.State == EntityState.Deleted ? "{ }" : GetAsJson(entry.CurrentValues)), TableName = tableName, IdentityJson = identityJson, DateCreated = DateTime.UtcNow, }; #if DEBUG if (audit.FromJson == audit.ToJson) { throw new Exception($"Something went wrong because this {audit.ChangeType} Audit shows no changes!"); } #endif audits.Add(audit); } // This is the reason why you must not add changes to context. You must accept // old changes prior to adding your new audit records otherwise EF will perform // changes again. If you add your entities to context and call accept before // saving them your changes will be lost context.AcceptAllChanges(); // Now add all audits from list to context Audits.AddRange(audits); int result = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // Complete the transaction scope.Complete(); return(result); } }
public void AcceptAllChanges() { context.AcceptAllChanges(); }