Beispiel #1
0
        /// <summary>
        /// Save changes regardless of <see cref="DbUpdateConcurrencyException"/>.
        /// http://msdn.microsoft.com/en-us/data/jj592904.aspx
        /// </summary>
        /// <exception cref="DbUpdateConcurrencyException" />
        public static async Task SaveChangesIgnoreConcurrencyAsync(
            this DbContext dbContext, int retryCount = 3)
        {
            int errorCount = 0;

            for (;;)
            {
                try
                {
                    await dbContext.SaveChangesAsync();

                    break;
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    if (++errorCount > retryCount)
                    {
                        throw;
                    }
                    // update original values from the database
                    EntityEntry dbEntry = ex.Entries.Single();
                    dbEntry.OriginalValues.SetValues(await dbEntry.GetDatabaseValuesAsync());

                    UpdateRowVersionFromDb(dbEntry);
                }
            }
            ;
        }
Beispiel #2
0
        internal static async Task <EntityEntry> RefreshAsync(this EntityEntry tracking, RefreshConflict refreshMode)
        {
            switch (refreshMode)
            {
            case RefreshConflict.StoreWins:
            {
                await tracking.ReloadAsync();

                break;
            }

            case RefreshConflict.ClientWins:
            {
                PropertyValues databaseValues = await tracking.GetDatabaseValuesAsync();

                if (databaseValues == null)
                {
                    tracking.State = EntityState.Detached;
                }
                else
                {
                    tracking.OriginalValues.SetValues(databaseValues);
                }
                break;
            }

            case RefreshConflict.MergeClientAndStore:
            {
                PropertyValues databaseValues = await tracking.GetDatabaseValuesAsync();

                if (databaseValues == null)
                {
                    tracking.State = EntityState.Detached;
                }
                else
                {
                    PropertyValues originalValues = tracking.OriginalValues.Clone();
                    tracking.OriginalValues.SetValues(databaseValues);
                    databaseValues.Properties
                    .Where(property => !object.Equals(originalValues[property.Name], databaseValues[property.Name]))
                    .ForEach(property => tracking.Property(property.Name).IsModified = false);
                }
                break;
            }
            }
            return(tracking);
        }