private static bool AllMigrationsApplied(this Microsoft.EntityFrameworkCore.DbContext context) { var applied = context.GetService <IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService <IMigrationsAssembly>() .Migrations .Select(m => m.Key); return(!total.Except(applied).Any()); }
protected virtual void DiffSnapshot(ModelSnapshot snapshot, DbContext context) { var dependencies = context.GetService <ProviderConventionSetBuilderDependencies>(); var typeMappingConvention = new TypeMappingConvention(dependencies); typeMappingConvention.ProcessModelFinalizing(((IConventionModel)snapshot.Model).Builder, null); var relationalModelConvention = new RelationalModelConvention(); var sourceModel = relationalModelConvention.ProcessModelFinalized(snapshot.Model); var modelDiffer = context.GetService <IMigrationsModelDiffer>(); var operations = modelDiffer.GetDifferences(((IMutableModel)sourceModel).FinalizeModel(), context.Model); Assert.Equal(0, operations.Count); }
public void SaveChanges_calls_DetectChanges() { var services = new ServiceCollection() .AddScoped <IStateManager, FakeStateManager>() .AddScoped <IChangeDetector, FakeChangeDetector>(); var model = new ModelBuilder(new ConventionSet()).Entity <User>().Metadata.Model; var serviceProvider = InMemoryTestHelpers.Instance.CreateServiceProvider(services); using (var context = new DbContext( new DbContextOptionsBuilder() .UseInternalServiceProvider(serviceProvider) .UseInMemoryDatabase(Guid.NewGuid().ToString()) .UseModel(model) .Options)) { var changeDetector = (FakeChangeDetector)context.GetService <IChangeDetector>(); Assert.False(changeDetector.DetectChangesCalled); context.SaveChanges(); Assert.True(changeDetector.DetectChangesCalled); } }
public static int SubmitSaveChanges(this DbContext dbContext, bool acceptAllChangesOnSuccess = true) { dbContext.NotNull(nameof(dbContext)); CheckDisposed(dbContext); var dependencies = dbContext.GetService <IDbContextDependencies>(); dependencies.UpdateLogger.SaveChangesStarting(dbContext); TryDetectChanges(dbContext); try { var entitiesSaved = dependencies.StateManager.SaveChanges(acceptAllChangesOnSuccess); dependencies.UpdateLogger.SaveChangesCompleted(dbContext, entitiesSaved); return(entitiesSaved); } catch (DbUpdateConcurrencyException exception) { dependencies.UpdateLogger.OptimisticConcurrencyException(dbContext, exception); throw; } catch (Exception exception) { dependencies.UpdateLogger.SaveChangesFailed(dbContext, exception); throw; } }
/// <summary> /// Creates a proxy instance for an entity type if proxy creation has been turned on. /// </summary> /// <param name="context"> The <see cref="DbContext" />. </param> /// <param name="entityType"> The entity type for which a proxy is needed. </param> /// <param name="constructorArguments"> Arguments to pass to the entity type constructor. </param> /// <returns> The proxy instance. </returns> public static object CreateProxy( [NotNull] this DbContext context, [NotNull] Type entityType, [NotNull] params object[] constructorArguments) { Check.NotNull(context, nameof(context)); Check.NotNull(entityType, nameof(entityType)); Check.NotNull(constructorArguments, nameof(constructorArguments)); var options = context.GetService <IDbContextOptions>().FindExtension <ProxiesOptionsExtension>(); if (options?.UseLazyLoadingProxies != true) { throw new InvalidOperationException(ProxiesStrings.ProxiesNotEnabled(entityType.ShortDisplayName())); } return(context.GetService <IProxyFactory>().Create(context, entityType, constructorArguments)); }
public static bool InitialMigrationApplied(this Microsoft.EntityFrameworkCore.DbContext context) { var allAppliedMigrations = context.GetService <IHistoryRepository>() .GetAppliedMigrations() .Select(x => x.MigrationId) .ToArray(); return(allAppliedMigrations.Any(x => x.EndsWith(InitialMigrationId)) && !allAppliedMigrations.Contains(SeedInitialDataMigrationId)); }
protected virtual void DiffSnapshot(ModelSnapshot snapshot, DbContext context) { var sourceModel = snapshot.Model; var targetModel = context.Model; var modelDiffer = context.GetService <IMigrationsModelDiffer>(); var operations = modelDiffer.GetDifferences(sourceModel, targetModel); Assert.Equal(0, operations.Count); }
/// <summary> /// Creates a new instance of <see cref="SqlServerRetryingExecutionStrategy" />. /// </summary> /// <param name="context"> The context on which the operations will be invoked. </param> /// <param name="maxRetryCount"> The maximum number of retry attempts. </param> /// <param name="maxRetryDelay"> The maximum delay in milliseconds between retries. </param> /// <param name="errorNumbersToAdd"> Additional SQL error numbers that should be considered transient. </param> public SqlServerRetryingExecutionStrategy( [NotNull] DbContext context, int maxRetryCount, TimeSpan maxRetryDelay, [CanBeNull] ICollection <int> errorNumbersToAdd) : this(new ExecutionStrategyContext( context, context.GetService <IDbContextServices>().LoggerFactory.CreateLogger <IExecutionStrategy>()), maxRetryCount, maxRetryDelay, errorNumbersToAdd) { }
private static string CreateDebugView(DbContext context) { #if CORE50 var model = context.Model; return(model.AsModel().DebugView.LongView); #elif CORE60 return(context.GetService <IDesignTimeModel>().Model.ToDebugString(MetadataDebugStringOptions.LongDefault)); #else var model = context.Model; return(model.AsModel().DebugView.View); #endif }
/// <summary> /// Creates a new instance of <see cref="SqlServerRetryingExecutionStrategy" />. /// </summary> /// <param name="context"> The context on which the operations will be invoked. </param> /// <param name="maxRetryCount"> The maximum number of retry attempts. </param> /// <param name="maxRetryDelay"> The maximum delay in milliseconds between retries. </param> /// <param name="errorNumbersToAdd"> Additional SQL error numbers that should be considered transient. </param> public SqlServerRetryingExecutionStrategy( [NotNull] DbContext context, int maxRetryCount, TimeSpan maxRetryDelay, [CanBeNull] ICollection <int> errorNumbersToAdd) : this(new ExecutionStrategyContext( context.GetService <ExecutionStrategyContextDependencies>()), maxRetryCount, maxRetryDelay, errorNumbersToAdd) { }
protected virtual void DiffSnapshot(ModelSnapshot snapshot, DbContext context) { var sourceModel = snapshot.Model; var targetModel = context.Model; var typeMapper = context.GetService <IRelationalTypeMappingSource>(); foreach (var property in sourceModel.GetEntityTypes().SelectMany(e => e.GetDeclaredProperties())) { Assert.NotNull(typeMapper.FindMapping(property)); } foreach (var property in targetModel.GetEntityTypes().SelectMany(e => e.GetDeclaredProperties())) { Assert.NotNull(typeMapper.FindMapping(property)); } var modelDiffer = context.GetService <IMigrationsModelDiffer>(); var operations = modelDiffer.GetDifferences(sourceModel, targetModel); Assert.Equal(0, operations.Count); }
public void It_disposes_scope() { var fakeServiceProvider = new FakeServiceProvider(); var context = new DbContext( new DbContextOptionsBuilder().UseInternalServiceProvider(fakeServiceProvider).UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); var scopeService = Assert.IsType <FakeServiceProvider.FakeServiceScope>(context.GetService <IServiceScopeFactory>().CreateScope()); Assert.False(scopeService.Disposed); context.Dispose(); Assert.True(scopeService.Disposed); Assert.Throws <ObjectDisposedException>(() => ((IInfrastructure <IServiceProvider>)context).Instance); }
protected virtual async Task GiveMeSomeTimeAsync(DbContext db) { var stillExists = true; for (var i = 0; stillExists && i < 10; i++) { try { await Task.Delay(500); stillExists = await db.GetService <IRelationalDatabaseCreator>().ExistsAsync(); } catch { } } }
// Database deletion can happen as async file operation and SQLClient // doesn't account for this, so give some time for it to happen on slow C.I. machines protected virtual void GiveMeSomeTime(DbContext db) { var stillExists = true; for (var i = 0; stillExists && i < 10; i++) { try { Thread.Sleep(500); stillExists = db.GetService <IRelationalDatabaseCreator>().Exists(); } catch { } } }
public static async Task <int> SubmitSaveChangesAsync(this DbContext dbContext, bool acceptAllChangesOnSuccess = true, CancellationToken cancellationToken = default) { dbContext.NotNull(nameof(dbContext)); CheckDisposed(dbContext); var dependencies = dbContext.GetService <IDbContextDependencies>(); dependencies.UpdateLogger.SaveChangesStarting(dbContext); TryDetectChanges(dbContext); try { var entitiesSaved = await dependencies.StateManager .SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken) .ConfigureAwait(); dependencies.UpdateLogger.SaveChangesCompleted(dbContext, entitiesSaved); return(entitiesSaved); } catch (DbUpdateConcurrencyException exception) { dependencies.UpdateLogger.OptimisticConcurrencyException(dbContext, exception); throw; } catch (Exception exception) { dependencies.UpdateLogger.SaveChangesFailed(dbContext, exception); throw; } }