public void ConnectionOrigin_should_return_user_code_when_connection_string_initialization() { var contextInfo = new DbContextInfo(typeof(ContextWithConnectionString)); Assert.Equal(DbConnectionStringOrigin.UserCode, contextInfo.ConnectionStringOrigin); Assert.Null(contextInfo.ConnectionStringName); }
public void ConnectionOrigin_should_return_by_convention_when_compiled_model() { var contextInfo = new DbContextInfo(typeof(ContextWithCompiledModel)); Assert.Equal(DbConnectionStringOrigin.Convention, contextInfo.ConnectionStringOrigin); Assert.Equal("ProductivityApiUnitTests.DbContextInfoTests+ContextWithCompiledModel", contextInfo.ConnectionStringName); }
public void ConnectionOrigin_should_return_by_convention_when_named_initialization() { var contextInfo = new DbContextInfo(typeof(ContextWithoutDefaultCtor)); Assert.Equal(DbConnectionStringOrigin.Convention, contextInfo.ConnectionStringOrigin); Assert.Equal("foo", contextInfo.ConnectionStringName); }
public void ConnectionOrigin_should_return_configuration_when_connection_string_configured() { var contextInfo = new DbContextInfo(typeof(ContextWithConfiguredConnectionString)); Assert.Equal(DbConnectionStringOrigin.Configuration, contextInfo.ConnectionStringOrigin); Assert.Equal("ShortNameDbContext", contextInfo.ConnectionStringName); }
public void ConnectionString_and_ConnectionName_should_return_values_when_context_constructible() { var contextInfo = new DbContextInfo(typeof(SimpleContext)); Assert.True(!string.IsNullOrWhiteSpace(contextInfo.ConnectionString)); Assert.Equal("ProductivityApiUnitTests.DbContextInfoTests+SimpleContext", contextInfo.ConnectionStringName); }
public void CreateInstance_should_return_valid_instance_when_context_constructible_via_factory() { var contextInfo = new DbContextInfo(typeof(ContextWithoutDefaultCtor)); Assert.True(contextInfo.IsConstructible); Assert.Same(typeof(ContextWithoutDefaultCtor), contextInfo.CreateInstance().GetType()); }
public void CreateInstance_should_return_null_when_context_not_constructible() { var contextInfo = new DbContextInfo(typeof(DbContext)); Assert.False(contextInfo.IsConstructible); Assert.Null(contextInfo.CreateInstance()); }
public void CreateInstance_should_return_valid_instance_when_context_constructible() { var contextInfo = new DbContextInfo(typeof(SimpleContext)); Assert.True(contextInfo.IsConstructible); Assert.Same(typeof(SimpleContext), contextInfo.CreateInstance().GetType()); }
public void ConnectionOrigin_should_return_user_code_when_existing_object_context() { var contextInfo = new DbContextInfo(typeof(ContextWithExistingObjectContext)); Assert.Equal(DbConnectionStringOrigin.UserCode, contextInfo.ConnectionStringOrigin); Assert.Null(contextInfo.ConnectionStringName); }
public void ConnectionOrigin_should_return_user_code_when_existing_connection_and_compiled_model() { var contextInfo = new DbContextInfo(typeof(ContextWithExistingConnectionAndCompiledModel)); Assert.Equal(DbConnectionStringOrigin.UserCode, contextInfo.ConnectionStringOrigin); Assert.Null(contextInfo.ConnectionStringName); }
public Parser(Assembly assembly, string dbContextTypeName = null) { Debugger.Break(); this.assembly = assembly; Type contextType; if (dbContextTypeName != null) { log.Debug($"dbContextTypeName parameter is {dbContextTypeName}"); contextType = assembly.GetExportedTypes().FirstOrDefault(t => t.FullName == dbContextTypeName || t.Name == dbContextTypeName); log.Info($"Using contextType = {contextType.FullName}"); } else { log.Debug("dbContextTypeName parameter is null"); List <Type> types = assembly.GetExportedTypes().Where(t => typeof(DbContext).IsAssignableFrom(t) && !t.FullName.Contains("`")).ToList(); if (types.Count == 0) { log.Error($"No usable DBContext found in {assembly.FullName}"); throw new ArgumentException("Couldn't find DbContext-derived class in assembly. Is it public?"); } if (types.Count > 1) { log.Error($"Found more than one class derived from DbContext: {string.Join(", ", types.Select(t => t.FullName))}"); throw new AmbiguousMatchException("Found more than one class derived from DbContext"); } contextType = types[0]; log.Info($"Using contextType = {contextType.FullName}"); } ConstructorInfo constructor = contextType.GetConstructor(new[] { typeof(string) }); // ReSharper disable once UnthrowableException if (constructor == null) { log.Error("Can't find constructor with one string parameter (connection string or connection name)"); throw new MissingMethodException("Can't find constructor with one string parameter (connection string or connection name)"); } try { DbContextInfo dbContextInfo = new DbContextInfo(contextType, new DbProviderInfo("System.Data.SqlClient", "2008")); dbContext = dbContextInfo.CreateInstance(); } catch (InvalidOperationException e) { dbContext = assembly.CreateInstance(contextType.FullName, false, BindingFlags.Default, null, new object[] { "App=EntityFramework" }, null, null) as DbContext ?? throw new Exception($"Failed to create an instance of {contextType.FullName}. " + "Please ensure it has either a default constructor or a constructor with one string parameter (connection string or connection name)" , e); } metadata = ((IObjectContextAdapter)dbContext).ObjectContext.MetadataWorkspace; }
public TContext CreateContext <TContext>() where TContext : DbContext { var contextInfo = new DbContextInfo( typeof(TContext), new DbConnectionInfo(TestDatabase.ConnectionString, TestDatabase.ProviderName)); return((TContext)contextInfo.CreateInstance()); }
public void ConnectionString_and_ConnectionName_should_return_nulls_when_context_not_constructible() { var contextInfo = new DbContextInfo(typeof(DbContext)); Assert.False(contextInfo.IsConstructible); Assert.Null(contextInfo.ConnectionString); Assert.Null(contextInfo.ConnectionStringName); }
/// <summary> /// For testing. /// </summary> internal DbMigrator(DbContext usersContext = null, DbProviderFactory providerFactory = null) : base(null) { _contextForInterception = usersContext; _providerFactory = providerFactory; _usersContextInfo = new DbContextInfo(typeof(DbContext)); _configuration = new DbMigrationsConfiguration(); }
internal DbMigrator( DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, bool calledByCreateDatabase) : base((MigratorBase)null) { Check.NotNull <DbMigrationsConfiguration>(configuration, nameof(configuration)); Check.NotNull <Type>(configuration.ContextType, "configuration.ContextType"); this._configuration = configuration; this._calledByCreateDatabase = calledByCreateDatabase; this._existenceState = existenceState; if (usersContext != null) { this._usersContextInfo = new DbContextInfo(usersContext, (Func <IDbDependencyResolver>)null); } else { this._usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (!this._usersContextInfo.IsConstructible) { throw Error.ContextNotConstructible((object)configuration.ContextType); } } this._modelDiffer = this._configuration.ModelDiffer; DbContext context = usersContext ?? this._usersContextInfo.CreateInstance(); this._usersContext = context; try { this._migrationAssembly = new MigrationAssembly(this._configuration.MigrationsAssembly, this._configuration.MigrationsNamespace); this._currentModel = context.GetModel(); DbConnection connection = context.Database.Connection; this._providerFactory = DbProviderServices.GetProviderFactory(connection); this._defaultSchema = context.InternalContext.DefaultSchema ?? "dbo"; this._historyContextFactory = this._configuration.GetHistoryContextFactory(this._usersContextInfo.ConnectionProviderName); this._historyRepository = new HistoryRepository(context.InternalContext, this._usersContextInfo.ConnectionString, this._providerFactory, this._configuration.ContextKey, this._configuration.CommandTimeout, this._historyContextFactory, ((IEnumerable <string>) new string[1] { this._defaultSchema }).Concat <string>(this.GetHistorySchemas()), this._usersContext, this._existenceState); this._providerManifestToken = context.InternalContext.ModelProviderInfo != null ? context.InternalContext.ModelProviderInfo.ProviderManifestToken : DbConfiguration.DependencyResolver.GetService <IManifestTokenResolver>().ResolveManifestToken(connection); DbModelBuilder modelBuilder = context.InternalContext.CodeFirstModel.CachedModelBuilder; this._modificationCommandTreeGenerator = new Lazy <ModificationCommandTreeGenerator>((Func <ModificationCommandTreeGenerator>)(() => new ModificationCommandTreeGenerator(modelBuilder.BuildDynamicUpdateModel(new DbProviderInfo(this._usersContextInfo.ConnectionProviderName, this._providerManifestToken)), this.CreateConnection()))); DbInterceptionContext interceptionContext = new DbInterceptionContext().WithDbContext(this._usersContext); this._targetDatabase = Strings.LoggingTargetDatabaseFormat((object)DbInterception.Dispatch.Connection.GetDataSource(connection, interceptionContext), (object)DbInterception.Dispatch.Connection.GetDatabase(connection, interceptionContext), (object)this._usersContextInfo.ConnectionProviderName, this._usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo ? (object)Strings.LoggingExplicit : (object)this._usersContextInfo.ConnectionStringOrigin.ToString()); this._legacyContextKey = context.InternalContext.DefaultContextKey; this._emptyModel = this.GetEmptyModel(); } finally { if (usersContext == null) { this._usersContext = (DbContext)null; context.Dispose(); } } }
public void Can_use_custom_on_model_creating_action_to_configure_model_builder() { var contextInfo = new DbContextInfo(typeof(ContextWithExternalOnModelCreating2)); var objectContext = ((IObjectContextAdapter)contextInfo.CreateInstance()).ObjectContext; Assert.NotNull(objectContext); Assert.False(objectContext.CreateDatabaseScript().Contains("EdmMetadata")); }
// TODO: [Fact(Skip = "SDE Merge - No partial trust yet")] public void DbContextInfo_works_under_partial_trust() { var contextInfo = new DbContextInfo( typeof(AdvancedPatternsMasterContext), ProviderRegistry.Sql2008_ProviderInfo); var context = contextInfo.CreateInstance(); Assert.NotNull(context); }
public void ApplyContextInfo(DbContextInfo info) { if (this._contextInfo != null) { return; } this.InitializerDisabled = true; this._contextInfo = info; this._contextInfo.ConfigureContext(this.Owner); }
private static DbContext CreateContext() { var info = new DbContextInfo(typeof(TestContext), new DbProviderInfo("System.Data.SqlClient", "2012")); var ctx = info.CreateInstance(); ctx.Database.Connection.ConnectionString = "Data Source=.\notneeded;Initial Catalog=EfUnitTest;Integrated Security=True"; return(ctx); }
public void DbContextInfo_can_provide_a_database_first_model() { using (var context = new DbContextInfo( typeof(DatabaseFirstContext), AddConnectionStrings(CreateEmptyConfig())).CreateInstance()) { // Will throw if DbFirstConnectionString is not found and used. var objectContext = ((IObjectContextAdapter)context).ObjectContext; Assert.Equal("AdvancedPatternsModelFirstContext", objectContext.DefaultContainerName); } }
protected virtual TConfig CreateConfiguration() { var config = new TConfig(); if (this.ConnectionString.HasValue()) { var dbContextInfo = new DbContextInfo(typeof(TContext)); config.TargetDatabase = new DbConnectionInfo(this.ConnectionString, dbContextInfo.ConnectionProviderName); } return(config); }
public void DbContextInfo_can_provide_a_code_first_model_without_hitting_the_database() { Database.SetInitializer <CodeFirstContext>(null); using (var context = new DbContextInfo( typeof(CodeFirstContext), new DbProviderInfo("System.Data.SqlClient", "2008")).CreateInstance()) { var objectContext = ((IObjectContextAdapter)context).ObjectContext; Assert.Equal("CodeFirstContext", objectContext.DefaultContainerName); } }
protected override void InitializeContext() { this.CheckContextNotDisposed(); if (this._objectContext != null) { return; } if (this._creatingModel) { throw Error.DbContext_ContextUsedInModelCreating(); } try { DbContextInfo currentInfo = DbContextInfo.CurrentInfo; if (currentInfo != null) { this.ApplyContextInfo(currentInfo); } this._creatingModel = true; if (this._createdWithExistingModel) { if (this._internalConnection.ConnectionHasModel) { throw Error.DbContext_ConnectionHasModel(); } this._objectContext = this._model.CreateObjectContext <ObjectContext>(this._internalConnection.Connection); } else if (this._internalConnection.ConnectionHasModel) { this._objectContext = this._internalConnection.CreateObjectContextFromConnectionModel(); } else { IDbModelCacheKey key = this._cacheKeyFactory(this.Owner); DbCompiledModel dbCompiledModel = LazyInternalContext._cachedModels.GetOrAdd(key, (Func <IDbModelCacheKey, RetryLazy <LazyInternalContext, DbCompiledModel> >)(t => new RetryLazy <LazyInternalContext, DbCompiledModel>(new Func <LazyInternalContext, DbCompiledModel>(LazyInternalContext.CreateModel)))).GetValue(this); this._objectContext = dbCompiledModel.CreateObjectContext <ObjectContext>(this._internalConnection.Connection); this._model = dbCompiledModel; } this._objectContext.ContextOptions.EnsureTransactionsForFunctionsAndCommands = this._initialEnsureTransactionsForFunctionsAndCommands; this._objectContext.ContextOptions.LazyLoadingEnabled = this._initialLazyLoadingFlag; this._objectContext.ContextOptions.ProxyCreationEnabled = this._initialProxyCreationFlag; this._objectContext.ContextOptions.UseCSharpNullComparisonBehavior = !this._useDatabaseNullSemanticsFlag; this._objectContext.CommandTimeout = this._commandTimeout; this._objectContext.ContextOptions.UseConsistentNullReferenceBehavior = true; this._objectContext.InterceptionContext = this._objectContext.InterceptionContext.WithDbContext(this.Owner); this.ResetDbSets(); this._objectContext.InitializeMappingViewCacheFactory(this.Owner); } finally { this._creatingModel = false; } }
internal DbMigrator( DbContext usersContext = null, DbProviderFactory providerFactory = null, MigrationAssembly migrationAssembly = null) : base((MigratorBase)null) { this._usersContext = usersContext; this._providerFactory = providerFactory; this._migrationAssembly = migrationAssembly; this._usersContextInfo = new DbContextInfo(typeof(DbContext)); this._configuration = new DbMigrationsConfiguration(); this._calledByCreateDatabase = true; }
public void CreateDatabase_using_Migrations_does_not_suppress_initializers() { var internalContext = CreateMockContextForMigrator().Object; DbContextInfo.ClearInfoForContext(internalContext.Owner.GetType()); new DatabaseCreator().CreateDatabase( internalContext, (config, context) => new Mock <DbMigrator>(config, context, DatabaseExistenceState.Unknown).Object, null); Assert.Null(DbContextInfo.TryGetInfoForContext(internalContext.Owner.GetType())); }
public void CreateInstance_should_use_passed_connection_string_even_when_provider_info_is_passed_as_well() { var config = AddConnectionStrings( CreateEmptyConfig().AddDefaultConnectionFactory( "ProductivityApiUnitTests.FakeDbContextInfoConnectionFactory, EntityFramework.UnitTests", new string[0])); var contextInfo = new DbContextInfo(typeof(ContextWithoutDefaultCtor), config, ProviderRegistry.SqlCe4_ProviderInfo); Assert.Equal(DbConnectionStringOrigin.Configuration, contextInfo.ConnectionStringOrigin); Assert.Equal("Initial Catalog=foo", contextInfo.ConnectionString); Assert.Equal("foo", contextInfo.ConnectionStringName); }
// <summary> // For testing. // </summary> internal DbMigrator( DbContext usersContext = null, DbProviderFactory providerFactory = null, MigrationAssembly migrationAssembly = null) : base(null) { _contextForInterception = usersContext; _providerFactory = providerFactory; _migrationAssembly = migrationAssembly; _usersContextInfo = new DbContextInfo(typeof(DbContext)); _configuration = new DbMigrationsConfiguration(); _calledByCreateDatabase = true; }
public void CreateInstance_should_use_passed_provider_info_when_building_model() { var contextInfo = new DbContextInfo(typeof(SimpleContext), ProviderRegistry.SqlCe4_ProviderInfo); Assert.Equal(ProviderRegistry.SqlCe4_ProviderInfo.ProviderInvariantName, contextInfo.ConnectionProviderName); Assert.Equal(string.Empty, contextInfo.ConnectionString); Database.SetInitializer <SimpleContext>(null); var objectContext = ((IObjectContextAdapter)contextInfo.CreateInstance()).ObjectContext; Assert.NotNull(objectContext); Assert.Equal("SqlCeConnection", ((EntityConnection)objectContext.Connection).StoreConnection.GetType().Name); }
/// <summary> /// Initializes a new instance of the <see cref="DbMigrator"/> class. /// </summary> /// <param name="configuration">Configuration to be used for the migration process.</param> public DbMigrator(DbMigrationsConfiguration configuration) : base(configuration) { _usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (_usersContextInfo.IsConstructible) { using (var context = _usersContextInfo.CreateInstance()) { DbMigrationContext.Current.DatabaseName = context.Database.Connection.Database; } } }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(object sender, EventArgs e) { var userConfig = this._dte2.SelectedItems.Item(1).ProjectItem.ContainingProject.GetProjectConfiguration(); DynamicTypeService typeService; IVsSolution solutionService; IVsHierarchy projectHierarchy; using (ServiceProvider serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider) this._dte2.DTE)) { typeService = (DynamicTypeService)serviceProvider.GetService(typeof(DynamicTypeService)); solutionService = (IVsSolution)serviceProvider.GetService(typeof(SVsSolution)); } int uniqueProjectName = solutionService.GetProjectOfUniqueName(this._dte2.SelectedItems.Item(1).ProjectItem.ContainingProject.UniqueName, out projectHierarchy); if (uniqueProjectName != 0) { throw Marshal.GetExceptionForHR(uniqueProjectName); } ITypeResolutionService resolutionService = typeService.GetTypeResolutionService(projectHierarchy); try { var itemNamespace = this._dte2.SelectedItems.Item(1)?.ProjectItem?.GetNameSpace(); Type type = resolutionService.GetType($"{itemNamespace.FullName}.{_fileName}"); var dbContextInfo = new DbContextInfo(type, userConfig); var filePath = $"{_fileDirectory}\\{_fileName}.edmx"; using (var writer = new XmlTextWriter(filePath, Encoding.Default)) { EdmxWriter.WriteEdmx(dbContextInfo.CreateInstance(), writer); } _dte2.ItemOperations.OpenFile(filePath); } catch (Exception ex) { IVsUIShell uiShell = (IVsUIShell)Package.GetGlobalService(typeof(SVsUIShell)); Guid clsid = Guid.Empty; int result; uiShell.ShowMessageBox(0, ref clsid, "Ef Model Generator", string.Format(CultureInfo.CurrentCulture, "Inside {0}.Initialize()", this.GetType().FullName), ex.ToString(), 0, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_INFO, 0, out result); } }