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_via_factory() { var contextInfo = new DbContextInfo(typeof(ContextWithoutDefaultCtor)); Assert.True(contextInfo.IsConstructible); Assert.Same(typeof(ContextWithoutDefaultCtor), contextInfo.CreateInstance().GetType()); }
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 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 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); }
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 CreateInstance_should_attach_on_model_creating_custom_action_and_invoke_once() { var calledCount = 0; var contextInfo = new DbContextInfo(typeof(ContextWithExternalOnModelCreating1)); contextInfo.OnModelCreating = _ => calledCount++; contextInfo.CreateInstance(); Assert.Equal(0, calledCount); var objectContext = ((IObjectContextAdapter)contextInfo.CreateInstance()).ObjectContext; Assert.NotNull(objectContext); Assert.Equal(1, calledCount); objectContext = ((IObjectContextAdapter)contextInfo.CreateInstance()).ObjectContext; Assert.NotNull(objectContext); Assert.Equal(1, calledCount); }
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); } }
public void Can_set_hard_coded_connection() { var connection = new DbConnectionInfo("Database=UseThisDatabaseInstead", "System.Data.SqlClient"); var contextInfo = new DbContextInfo(typeof(SimpleContext), connection); Assert.Equal(DbConnectionStringOrigin.DbContextInfo, contextInfo.ConnectionStringOrigin); Assert.Equal("System.Data.SqlClient", contextInfo.ConnectionProviderName); Assert.Equal(null, contextInfo.ConnectionStringName); Assert.True(contextInfo.IsConstructible); using (var context = contextInfo.CreateInstance()) { Assert.Equal("UseThisDatabaseInstead", context.Database.Connection.Database); } }
public void Can_set_hard_coded_connection_from_default_config() { var connection = new DbConnectionInfo("OverrideConnectionTest"); var contextInfo = new DbContextInfo(typeof(SimpleContext), connection); Assert.Equal(DbConnectionStringOrigin.DbContextInfo, contextInfo.ConnectionStringOrigin); Assert.Equal("System.Data.SqlClient", contextInfo.ConnectionProviderName); Assert.Equal("OverrideConnectionTest", contextInfo.ConnectionStringName); Assert.True(contextInfo.IsConstructible); using (var context = contextInfo.CreateInstance()) { Assert.Equal("ConnectionFromAppConfig", context.Database.Connection.Database); } }
public void EdmxWriter_can_write_an_EDMX_when_DbContextInfo_is_used_to_specify_the_provider_info() { var contextInfo = new DbContextInfo( typeof(SimpleModelContext), new DbProviderInfo("System.Data.SqlClient", "2008")); using (var context = contextInfo.CreateInstance()) { var edmxBuilder = new StringBuilder(); EdmxWriter.WriteEdmx(context, XmlWriter.Create(edmxBuilder)); SanityCheckEdmx(edmxBuilder); } }
public void Supplied_config_used_to_load_original_and_overriden_connection() { var connection = new DbConnectionInfo("GetMeFromSuppliedConfig"); var contextInfo = new DbContextInfo( typeof(ContextWithConnectionNameNotInAppConfigFile), CreateEmptyConfig() .AddConnectionString("GetMeFromSuppliedConfig", "Database=ConnectionFromSuppliedConfig", "System.Data.SqlClient") .AddConnectionString("WontFindMeInDefaultConfig", "Database=WontFindMeInDefaultConfig", "System.Data.SqlClient"), connection); using (var context = contextInfo.CreateInstance()) { Assert.Equal("ConnectionFromSuppliedConfig", context.Database.Connection.Database); } }
public void Can_unset_custom_on_model_creating_action() { var contextInfo = new DbContextInfo( typeof(ContextWithExternalOnModelCreating3)) { OnModelCreating = mb => mb.Ignore <FakeEntity>() }; contextInfo.OnModelCreating = null; var objectContext = ((IObjectContextAdapter)contextInfo.CreateInstance()).ObjectContext; Assert.NotNull(objectContext); Assert.True(objectContext.CreateDatabaseScript().Contains("FakeEntities")); }
public void CreateInstance_should_use_passed_provider_info_when_building_model_even_when_config_is_passed_as_well() { var config = AddConnectionStrings( CreateEmptyConfig().AddDefaultConnectionFactory( "ProductivityApiUnitTests.FakeDbContextInfoConnectionFactory, EntityFramework.UnitTests", new string[0])); var contextInfo = new DbContextInfo(typeof(SimpleContext), config, 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); }
public void Can_set_hard_coded_connection_from_supplied_config() { var connection = new DbConnectionInfo("GetMeFromSuppliedConfig"); var contextInfo = new DbContextInfo( typeof(SimpleContext), CreateEmptyConfig().AddConnectionString( "GetMeFromSuppliedConfig", "Database=ConnectionFromSuppliedConfig", "System.Data.SqlClient"), connection); Assert.Equal(DbConnectionStringOrigin.DbContextInfo, contextInfo.ConnectionStringOrigin); Assert.Equal("System.Data.SqlClient", contextInfo.ConnectionProviderName); Assert.Equal("GetMeFromSuppliedConfig", contextInfo.ConnectionStringName); Assert.True(contextInfo.IsConstructible); using (var context = contextInfo.CreateInstance()) { Assert.Equal("ConnectionFromSuppliedConfig", context.Database.Connection.Database); } }
protected override DbContext CreateDbContext() { DbContextInfo contextInfo = new DbContextInfo(typeof(VehicleAdministrationDbContext), new DbProviderInfo(providerInvariantName: "System.Data.SqlClient", providerManifestToken: "2008")); return(contextInfo.CreateInstance()); }
internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext) : base(null) { Check.NotNull(configuration, "configuration"); Check.NotNull(configuration.ContextType, "configuration.ContextType"); _configuration = configuration; _calledByCreateDatabase = usersContext != null; // If DbContext CreateDatabase is using Migrations then the user has not opted out of initializers // and if we disable the initializer here then future calls to Initialize the database (for this or // a different connection) will fail. So only disable the initializer if Migrations are being used // explicitly. if (usersContext == null) { DisableInitializer(_configuration.ContextType); } if (_calledByCreateDatabase) { _usersContextInfo = new DbContextInfo(usersContext); } else { _usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (!_usersContextInfo.IsConstructible) { throw Error.ContextNotConstructible(configuration.ContextType); } } _modelDiffer = _configuration.ModelDiffer; var context = usersContext ?? _usersContextInfo.CreateInstance(); try { _migrationAssembly = new MigrationAssembly(_configuration.MigrationsAssembly, _configuration.MigrationsNamespace); _currentModel = context.GetModel(); var connection = context.Database.Connection; _providerFactory = DbProviderServices.GetProviderFactory(connection); var defaultSchema = context.InternalContext.DefaultSchema; var historySchemas = GetHistorySchemas(); if (!string.IsNullOrWhiteSpace(defaultSchema)) { historySchemas = historySchemas.Concat(new[] { defaultSchema }); } _historyRepository = new HistoryRepository( _usersContextInfo.ConnectionString, _providerFactory, _configuration.ContextKey, historySchemas, _migrationAssembly.MigrationIds.Any() ? _configuration.HistoryContextFactory : null); _providerManifestToken = context.InternalContext.ModelProviderInfo != null ? context.InternalContext.ModelProviderInfo.ProviderManifestToken : DbConfiguration .GetService <IManifestTokenService>() .GetProviderManifestToken(connection); _targetDatabase = Strings.LoggingTargetDatabaseFormat( connection.DataSource, connection.Database, _usersContextInfo.ConnectionProviderName, _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo ? Strings.LoggingExplicit : _usersContextInfo.ConnectionStringOrigin.ToString()); _legacyContextKey = context.InternalContext.ContextKey; _currentHistoryModel = GetCurrentHistoryModel(defaultSchema); _initialHistoryModel = GetInitialHistoryModel(); _emptyModel = GetEmptyModel(); AttachHistoryModel(_currentModel); } finally { if (usersContext == null) { context.Dispose(); } } }
protected override DbContext CreateDbContext() { var contextInfo = new DbContextInfo(typeof(CubeDbContext), new DbConnectionInfo(nameof(CubeDbContext), "System.Data.SQLite")); return(contextInfo.CreateInstance()); }
internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext) : base(null) { Check.NotNull(configuration, "configuration"); Check.NotNull(configuration.ContextType, "configuration.ContextType"); _configuration = configuration; _calledByCreateDatabase = usersContext != null; // If DbContext CreateDatabase is using Migrations then the user has not opted out of initializers // and if we disable the initializer here then future calls to Initialize the database (for this or // a different connection) will fail. So only disable the initializer if Migrations are being used // explicitly. if (usersContext == null) { DisableInitializer(_configuration.ContextType); } if (_calledByCreateDatabase) { _usersContextInfo = new DbContextInfo(usersContext); } else { _usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (!_usersContextInfo.IsConstructible) { throw Error.ContextNotConstructible(configuration.ContextType); } } _modelDiffer = _configuration.ModelDiffer; var context = usersContext ?? _usersContextInfo.CreateInstance(); _contextForInterception = context; try { _migrationAssembly = new MigrationAssembly( _configuration.MigrationsAssembly, _configuration.MigrationsNamespace); _currentModel = context.GetModel(); var connection = context.Database.Connection; _providerFactory = DbProviderServices.GetProviderFactory(connection); _defaultSchema = context.InternalContext.DefaultSchema ?? EdmModelExtensions.DefaultSchema; _historyRepository = new HistoryRepository( _usersContextInfo.ConnectionString, _providerFactory, _configuration.ContextKey, _configuration.CommandTimeout, new[] { _defaultSchema }.Concat(GetHistorySchemas()), _configuration.HistoryContextFactory); _providerManifestToken = context.InternalContext.ModelProviderInfo != null ? context.InternalContext.ModelProviderInfo.ProviderManifestToken : DbConfiguration .GetService <IManifestTokenService>() .GetProviderManifestToken(connection); _modificationCommandTreeGenerator = new ModificationCommandTreeGenerator( context.GetDynamicUpdateModel( new DbProviderInfo( _usersContextInfo.ConnectionProviderName, _providerManifestToken)), CreateConnection()); _targetDatabase = Strings.LoggingTargetDatabaseFormat( connection.DataSource, connection.Database, _usersContextInfo.ConnectionProviderName, _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo ? Strings.LoggingExplicit : _usersContextInfo.ConnectionStringOrigin.ToString()); _legacyContextKey = context.InternalContext.ContextKey; _emptyModel = GetEmptyModel(); } finally { if (usersContext == null) { _contextForInterception = null; context.Dispose(); } } }
protected override DbContext CreateDbContext() { DbContextInfo contextInfo = new DbContextInfo(typeof(SimpleProjectManagerDbContext), new DbProviderInfo(providerInvariantName: "System.Data.SqlClient", providerManifestToken: "2008")); return(contextInfo.CreateInstance()); }
internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext) : base(null) { Check.NotNull(configuration, "configuration"); Check.NotNull(configuration.ContextType, "configuration.ContextType"); _configuration = configuration; _calledByCreateDatabase = usersContext != null; if (_calledByCreateDatabase) { _usersContextInfo = new DbContextInfo(usersContext); } else { _usersContextInfo = configuration.TargetDatabase == null ? new DbContextInfo(configuration.ContextType) : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase); if (!_usersContextInfo.IsConstructible) { throw Error.ContextNotConstructible(configuration.ContextType); } } _modelDiffer = _configuration.ModelDiffer; var context = usersContext ?? _usersContextInfo.CreateInstance(); _contextForInterception = context; try { _migrationAssembly = new MigrationAssembly( _configuration.MigrationsAssembly, _configuration.MigrationsNamespace); _currentModel = context.GetModel(); var connection = context.Database.Connection; _providerFactory = DbProviderServices.GetProviderFactory(connection); _defaultSchema = context.InternalContext.DefaultSchema ?? EdmModelExtensions.DefaultSchema; _historyContextFactory = _configuration .GetHistoryContextFactory(_usersContextInfo.ConnectionProviderName); _historyRepository = new HistoryRepository( _usersContextInfo.ConnectionString, _providerFactory, _configuration.ContextKey, _configuration.CommandTimeout, new[] { _defaultSchema }.Concat(GetHistorySchemas()), _contextForInterception, _historyContextFactory); _providerManifestToken = context.InternalContext.ModelProviderInfo != null ? context.InternalContext.ModelProviderInfo.ProviderManifestToken : DbConfiguration .DependencyResolver .GetService <IManifestTokenResolver>() .ResolveManifestToken(connection); var modelBuilder = context.InternalContext.CodeFirstModel.CachedModelBuilder; _modificationCommandTreeGenerator = new Lazy <ModificationCommandTreeGenerator>( () => new ModificationCommandTreeGenerator( modelBuilder.BuildDynamicUpdateModel( new DbProviderInfo( _usersContextInfo.ConnectionProviderName, _providerManifestToken)), CreateConnection())); _targetDatabase = Strings.LoggingTargetDatabaseFormat( connection.DataSource, connection.Database, _usersContextInfo.ConnectionProviderName, _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo ? Strings.LoggingExplicit : _usersContextInfo.ConnectionStringOrigin.ToString()); _legacyContextKey = context.InternalContext.DefaultContextKey; _emptyModel = GetEmptyModel(); } finally { if (usersContext == null) { _contextForInterception = null; context.Dispose(); } } }