protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseNpgsql("Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"); optionsBuilder.AddInterceptors(new SuppressCommandResultInterceptor()); optionsBuilder.AddInterceptors(new SuppressConnectionInterceptor()); optionsBuilder.EnableServiceProviderCaching(); base.OnConfiguring(optionsBuilder); }
public static DbContextOptionsBuilder AddInterceptorSoftDeleteDateTime( this DbContextOptionsBuilder optionsBuilder ) { return(optionsBuilder .AddInterceptors(new SoftDeleteDateTimeSaveChangesInterceptor())); }
public static DbContextOptions GetOptions(IEnumerable <IInterceptor> dbInterceptors = null) { var databaseName = nameof(EFCoreBulkTest); var optionsBuilder = new DbContextOptionsBuilder <TestContext>(); if (DbServer == DbServer.SqlServer) { var connectionString = $"Server=localhost;Database={databaseName};Trusted_Connection=True;MultipleActiveResultSets=true"; // ALTERNATIVELY (Using MSSQLLocalDB): //var connectionString = $@"Data Source=(localdb)\MSSQLLocalDB;Database={databaseName};Trusted_Connection=True;MultipleActiveResultSets=True"; optionsBuilder.UseSqlServer(connectionString); // Can NOT Test with UseInMemoryDb (Exception: Relational-specific methods can only be used when the context is using a relational) } else if (DbServer == DbServer.Sqlite) { string connectionString = $"Data Source={databaseName}.db"; optionsBuilder.UseSqlite(connectionString); // ALTERNATIVELY: //string connectionString = (new SqliteConnectionStringBuilder { DataSource = $"{databaseName}Lite.db" }).ToString(); //optionsBuilder.UseSqlite(new SqliteConnection(connectionString)); } else { throw new NotSupportedException($"Database {DbServer} is not supported. Only SQL Server and SQLite are Currently supported."); } if (dbInterceptors?.Any() == true) { optionsBuilder.AddInterceptors(dbInterceptors); } return(optionsBuilder.Options); }
public static TestDbContext CreateContext(string databaseGuid, ILoggerFactory?loggerFactory = null, IEnumerable <IInterceptor>?interceptors = null) { var connection = new SqliteConnection($"Data Source={databaseGuid.Replace("-", "")};Mode=Memory;Cache=Shared"); connection.Open(); var builder = new DbContextOptionsBuilder <TestDbContext>() .UseSqlite(connection) .ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)); if (loggerFactory != null) { builder.UseLoggerFactory(loggerFactory); } if (interceptors != null && interceptors.Any()) { builder.AddInterceptors(interceptors); } var context = new TestDbContext(builder.Options); context.Database.EnsureDeleted(); context.Database.EnsureCreated(); return(context); }
public PostgreSqlDatabaseProvider( string connectionString, string dbNamePrefix, string?templateDb, bool enableLogging, Func <TDbContext, Task>?seed, Action <NpgsqlDbContextOptionsBuilder>?npgsqlOptions, Action <DbContextOptionsBuilder <TDbContext> >?dbContextOptions) { this.connectionString = connectionString; this.templateDb = templateDb; this.seed = seed; //The max identifier length of postgres is 63 chars. Minus the 22 we're using from the base64-guid the prefix must be max 41 chars. if (dbNamePrefix.Length > 41) { throw new ArgumentException("The max. allowed length of the dbNamePrefix is 41 characters."); } dbName = dbNamePrefix + Convert.ToBase64String(Guid.NewGuid().ToByteArray()).TrimEnd('='); var testDbConnectionString = PostgreSqlUtil.ReplaceDatabaseName(connectionString, dbName); var builder = new DbContextOptionsBuilder <TDbContext>().UseNpgsql(testDbConnectionString, npgsqlOptions); dbContextOptions?.Invoke(builder); if (enableLogging) { builder.UseLoggerFactory(new LoggerFactory(new[] { new XUnitLoggerProvider() })); } builder.AddInterceptors(new CreateDatabaseInterceptor <TDbContext>(CreateDatabase)); options = builder.Options; }
public void TestPlayReplayInMemory() { string nameFileToRecord = "a.zip"; if (File.Exists(nameFileToRecord)) { File.Delete(nameFileToRecord); } var opt = new DbContextOptions <MyDataContext>(); var optionsBuilder = new DbContextOptionsBuilder(opt); optionsBuilder.AddInterceptors(new InterceptionRecordOrPlay(nameFileToRecord, ModeInterception.Record)); optionsBuilder.UseInMemoryDatabase(databaseName: "testing"); using var c = new MyDataContext(optionsBuilder.Options as DbContextOptions <MyDataContext>); c.PersonWithBlog.Add(new PersonWithBlog() { Id = 1, Name = "Andrei", Url = "http://msprogrammer.serviciipeweb.ro/" }); c.SaveChanges(); var q = c.PersonWithBlog.FirstOrDefault(it => it.Id == 1); Assert.NotNull(q); Assert.False(File.Exists(nameFileToRecord), "in memory is not database relational"); }
/// <summary> /// Add easy profiler for interceptions. /// </summary> /// <param name="optionsBuilder"> /// DbContextOptionsBuilder /// </param> /// <returns> /// DbContextOptionsBuilder. /// </returns> public static DbContextOptionsBuilder AddEasyProfiler(this DbContextOptionsBuilder optionsBuilder, IServiceCollection services) { var buildServices = services.BuildServiceProvider(); optionsBuilder.AddInterceptors(new EasyProfilerInterceptors(buildServices.GetService <IEasyProfilerBaseService <ProfilerDbContext> >(), buildServices.GetService <IHttpContextAccessor>())); return(optionsBuilder); }
public static void UseConfiguredSqLite ( this DbContextOptionsBuilder optionsBuilder, AppSettings appSettings, IServiceProvider serviceProvider) { var connectionString = appSettings.GetSQLiteDbConnectionString(); optionsBuilder.UseSqlite ( connectionString, sqlServerOptionsBuilder => { sqlServerOptionsBuilder.CommandTimeout((int)TimeSpan.FromMinutes(3).TotalSeconds); sqlServerOptionsBuilder.MigrationsAssembly(typeof(SqLiteServiceCollectionExtensions).Assembly .FullName); } ); optionsBuilder.UseInternalServiceProvider(serviceProvider); // It's added to access services from the dbcontext, remove it if you are using the normal `AddDbContext` and normal constructor dependency injection. optionsBuilder.AddInterceptors(new PersianYeKeCommandInterceptor()); optionsBuilder.ConfigureWarnings(warnings => { // ... }); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.AddInterceptors(_lastCommandTextInterceptor); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=.\\Demo.db", sqliteOptionsAction: opt => { opt.ExecutionStrategy(context => new ResilientExecutionStrategy(context, 3, TimeSpan.FromSeconds(2))); opt.CommandTimeout(2); }); optionsBuilder.AddInterceptors(new DelayInterceptor()); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(ConnectionString, p => p.CommandTimeout(GlobalContext.SystemConfig.DBCommandTimeout)); optionsBuilder.AddInterceptors(new DbCommandCustomInterceptor()); optionsBuilder.UseLoggerFactory(_loggerFactory); // 这里需要注意,不能采用这种写法:optionsBuilder.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole())); // 会导致内存泄露的问题 }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(constr, a => a.UseRelationalNulls(true)); optionsBuilder.AddInterceptors(cache); optionsBuilder.UseLoggerFactory(loggerFactory); base.OnConfiguring(optionsBuilder); }
/// <summary> /// The options to be used by a DbContext. /// </summary> /// <returns></returns> private DbContextOptions CreateDbContextOptions() { var optionsBuilder = new DbContextOptionsBuilder(); gate.Configuration.Update(optionsBuilder); optionsBuilder.AddInterceptors(new HintCommandInterceptor(gate)); return(optionsBuilder.Options); }
/// <summary> /// Add MiCake configure for EFCore.(include repository lifetime etc.) /// If you don't inherit <see cref="MiCakeDbContext"/>, you can use this extension method in your DbContent OnConfiguring(). /// </summary> /// <param name="optionsBuilder"></param> /// <param name="serviceProvider"></param> /// <returns></returns> public static DbContextOptionsBuilder AddMiCakeConfigure(this DbContextOptionsBuilder optionsBuilder, IServiceProvider serviceProvider) { if (serviceProvider != null) { optionsBuilder.AddInterceptors(new MiCakeEFCoreInterceptor(serviceProvider)); } return(optionsBuilder); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MyEFC_DB2;Integrated Security=True"); optionsBuilder.AddInterceptors(new MySaveChangesInterceptor()); } }
public static CourseDbContext GetSQLCourseContext() { DbContextOptionsBuilder <CourseDbContext> optionsBuilder = new DbContextOptionsBuilder <CourseDbContext>(); optionsBuilder.UseSqlServer($"Server=.\\Sql2019; Database=CourseDb;Integrated Security=true "); // .UseLazyLoadingProxies(); optionsBuilder.AddInterceptors(new CountDatabaseAccessInterceptor()); return(new CourseDbContext(optionsBuilder.Options)); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.AddInterceptors(_auditEntitiesSaveChangesInterceptor); optionsBuilder .LogTo(Console.WriteLine) .EnableDetailedErrors(); base.OnConfiguring(optionsBuilder); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { //optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;ConnectRetryCount=0"); optionsBuilder.UseInMemoryDatabase(databaseName: "testing"); optionsBuilder.AddInterceptors(new InterceptionRecordOrPlay("a.zip", ModeInterception.Record));; } //TODO: add configuring to table }
//public DbSet<DestinationNts> Destinations { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (optionsBuilder.IsConfigured) { return; } Configure(optionsBuilder); optionsBuilder.UseSqlServer(ConnectionString, x => x.UseNetTopologySuite()); optionsBuilder.AddInterceptors(new HintCommandInterceptor()); base.OnConfiguring(optionsBuilder); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //optionsBuilder.UseLoggerFactory() // TODO put this behaind configuration optionsBuilder.LogTo(Console.WriteLine) .EnableSensitiveDataLogging() .EnableDetailedErrors(); optionsBuilder.AddInterceptors(new DatabaseCommandInterceptor()); base.OnConfiguring(optionsBuilder); }
public static void UseConfiguredInMemoryDatabase( this DbContextOptionsBuilder optionsBuilder, SiteSettings siteSettings, IServiceProvider serviceProvider) { optionsBuilder.UseInMemoryDatabase(siteSettings.ConnectionStrings.LocalDb.InitialCatalog); optionsBuilder.UseInternalServiceProvider(serviceProvider); // It's added to access services from the dbcontext, remove it if you are using the normal `AddDbContext` and normal constructor dependency injection. optionsBuilder.AddInterceptors(new PersianYeKeCommandInterceptor()); optionsBuilder.ConfigureWarnings(warnings => { // ... }); }
/// <summary> /// 数据库数据库拦截器 /// </summary> /// <param name="interceptors">拦截器</param> /// <param name="options"></param> private static void AddInterceptors(IInterceptor[] interceptors, DbContextOptionsBuilder options) { // 添加拦截器 var interceptorList = DbProvider.GetDefaultInterceptors(); if (interceptors != null || interceptors.Length > 0) { interceptorList.AddRange(interceptors); } options.AddInterceptors(interceptorList.ToArray()); }
/// <summary> /// Add easy profiler for interceptions. /// </summary> /// <param name="optionsBuilder"> /// DbContextOptionsBuilder /// </param> /// <returns> /// DbContextOptionsBuilder. /// </returns> public static DbContextOptionsBuilder AddEasyProfiler(this DbContextOptionsBuilder optionsBuilder, IServiceCollection services) { var interceptors = typeof(ProfilerDbContext).Assembly.GetTypes().Where(x => typeof(DbCommandInterceptor).IsAssignableFrom(x) && x != typeof(DbConnectionInterceptor) && x.IsClass).ToList(); //foreach (var interceptor in interceptors) //{ // optionsBuilder.AddInterceptors(interceptor); //} optionsBuilder.AddInterceptors(new EasyProfilerInterceptors(services.BuildServiceProvider().GetService <IEasyProfilerService>())); return(optionsBuilder); }
public static DbContextOptionsBuilder <TDbContext> Build <TDbContext>() where TDbContext : DbContext { var builder = new DbContextOptionsBuilder <TDbContext>(); if (LocalDbLogging.SqlLoggingEnabled) { builder.AddInterceptors(interceptor); } builder.EnableSensitiveDataLogging(); builder.EnableDetailedErrors(); return(builder); }
public static void Configure(this DbContextOptionsBuilder optionsBuilder, BehlogSetting setting, IServiceProvider provider) { optionsBuilder.UseSqlServer(setting.GetConnectionString(), __ => { __.CommandTimeout((int)TimeSpan.FromMinutes(3).TotalSeconds); __.EnableRetryOnFailure(); __.MigrationsAssembly(typeof(SqlServerContextFactory).Assembly.FullName); }); optionsBuilder.UseInternalServiceProvider(provider); optionsBuilder.AddInterceptors(new PersianDataCommandInterceptor()); }
protected override void OnConfiguring(DbContextOptionsBuilder builder) { base.OnConfiguring(builder); builder.UseSqlServer(_options.ConnectionString, options => { options.MigrationsHistoryTable("__EFMigrationsHistory", EntityTypeBuilderExtensions.SchemaName); }); if (_loggerFactory != null) { builder.UseLoggerFactory(_loggerFactory); } builder.AddInterceptors(new QueryCommandInterceptor()); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer(ConnectionString); optionsBuilder.UseLoggerFactory(Logger); // Magically make queries faster! optionsBuilder.AddInterceptors(new SpeedInterceptor()); // Always use bigint for TimeSpan columns. ValueConverters.Add(typeof(TimeSpan), new TimeSpanToTicksConverter()); }
internal bool EnableDatabaseTracking(DbContextOptionsBuilder <ApplicationDbContext> databaseOptionsBuilder) { if (!IsDatabaseTrackingEnabled()) { return(false); } databaseOptionsBuilder.AddInterceptors( new DatabaseTelemetryInterceptor( TelemetryConfigurationHelper.InitTelemetryClient( _appSettings.ApplicationInsightsInstrumentationKey, _appSettings.ApplicationType.ToString(), _logger, _telemetryClient) ) ); return(true); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // Select 1 provider optionsBuilder .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=BloggingDemo;Trusted_Connection=True;Connect Timeout=5;ConnectRetryCount=0") //.UseSqlite("filename=BloggingDemo.db") //.UseCosmos("https://*****:*****@"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==", "BloggingDemo") .EnableSensitiveDataLogging(); if (_logCommand) { optionsBuilder.UseLoggerFactory(ContextLoggerFactory); } optionsBuilder.AddInterceptors(new MyCommandInterceptor()); }
private static void ConfigureDbOptions(string connectionString, DbContextOptionsBuilder options) { //TODO: When OnConfiguring no longer has this we should renable this options.UseMySql(connectionString, optionsBuilder => { optionsBuilder.MaxBatchSize(4000); optionsBuilder.MinBatchSize(20); optionsBuilder.EnableRetryOnFailure(5); optionsBuilder.CommandTimeout(1000); optionsBuilder.MigrationsAssembly("FreecraftCore.DBC.Management"); }); options.AddInterceptors(new ForeignKeyIgnoreInterceptor()); options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); options.EnableSensitiveDataLogging(); }