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 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 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_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_by_convention_when_compiled_model()
        {
            var contextInfo = new DbContextInfo(typeof(ContextWithCompiledModel));

            Assert.Equal(DbConnectionStringOrigin.Convention, contextInfo.ConnectionStringOrigin);
            Assert.Equal(typeof(ContextWithCompiledModel).FullName, 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_valid_instance_when_context_constructible()
        {
            var contextInfo = new DbContextInfo(typeof(SimpleContext));

            Assert.True(contextInfo.IsConstructible);
            Assert.Same(typeof(SimpleContext), contextInfo.CreateInstance().GetType());
        }
        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(typeof(SimpleContext).FullName, contextInfo.ConnectionStringName);
        }
        public void CreateInstance_should_return_null_when_context_not_constructible()
        {
            var contextInfo = new DbContextInfo(typeof(DbContext));

            Assert.False(contextInfo.IsConstructible);
            Assert.Null(contextInfo.CreateInstance());
        }
Exemplo n.º 10
0
        internal static void MapContextToInfo(Type contextType, DbContextInfo info)
        {
            DebugCheck.NotNull(contextType);
            DebugCheck.NotNull(info);

            _infoMapping.AddOrUpdate(contextType, info, (t, i) => info);
        }
        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 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);
        }
Exemplo n.º 13
0
 /// <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();
 }
        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"));
        }
Exemplo n.º 15
0
        // 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 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);
     }
 }
        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);
            }
        }
Exemplo n.º 18
0
 // <summary>
 // For testing.
 // </summary>
 internal DbMigrator(
     DbContext usersContext = null,
     DbProviderFactory providerFactory = null,
     MigrationAssembly migrationAssembly = null)
     : base(null)
 {
     _usersContext = usersContext;
     _providerFactory = providerFactory;
     _migrationAssembly = migrationAssembly;
     _usersContextInfo = new DbContextInfo(typeof(DbContext));
     _configuration = new DbMigrationsConfiguration();
     _calledByCreateDatabase = true;
 }
        public void CreateInstance_should_use_passed_connection_string_even_when_provider_info_is_passed_as_well()
        {
            var config = AddConnectionStrings(
                CreateEmptyConfig().AddDefaultConnectionFactory(
                    typeof(FakeDbContextInfoConnectionFactory).FullName + ", 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);
        }
        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);
        }
        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 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);
            }
        }
Exemplo n.º 23
0
        /// <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;
				}
			}

		}
        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_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 Should_select_connection_string_from_supplied_candidates()
        {
            var connectionStringSettings
                = new ConnectionStringSettingsCollection
                {
                new ConnectionStringSettings("foo", "Initial Catalog=foo", "System.Data.SqlClient")
                };

#pragma warning disable 618 // Obsolete ctor
            var contextInfo = new DbContextInfo(typeof(ContextWithoutDefaultCtor), connectionStringSettings);
#pragma warning restore 618

            Assert.Equal(DbConnectionStringOrigin.Configuration, contextInfo.ConnectionStringOrigin);
            Assert.Equal("Initial Catalog=foo", contextInfo.ConnectionString);
            Assert.Equal("foo", contextInfo.ConnectionStringName);
        }
        public void Should_use_use_default_DefaultConnectionFactory_if_supplied_config_contains_no_DefaultConnectionFactory()
        {
            RunTestWithConnectionFactory(
                Database.ResetDefaultConnectionFactory,
                () =>
            {
                var config = CreateEmptyConfig();

                var contextInfo = new DbContextInfo(typeof(ContextWithoutDefaultCtor), config);

                Assert.Equal(DbConnectionStringOrigin.Convention, contextInfo.ConnectionStringOrigin);
                Assert.True(contextInfo.ConnectionString.Contains(@"Data Source=.\SQLEXPRESS"));
                Assert.True(contextInfo.ConnectionString.Contains(@"Initial Catalog=foo"));
                Assert.Equal("System.Data.SqlClient", contextInfo.ConnectionProviderName);
            });
        }
        public void DbContextInfo_should_get_connection_info_from_given_existing_context()
        {
            var mockContext = new Mock <InternalContextForMock <SimpleContext> >();

            mockContext.Setup(m => m.ConnectionStringOrigin).Returns(DbConnectionStringOrigin.UserCode);
            mockContext.Setup(m => m.ProviderName).Returns("My.Provider");
            mockContext.Setup(m => m.OriginalConnectionString).Returns("Databse=Foo");
            mockContext.Setup(m => m.ConnectionStringName).Returns("SomeName");

            var contextInfo = new DbContextInfo(mockContext.Object.Owner);

            Assert.Equal(DbConnectionStringOrigin.UserCode, contextInfo.ConnectionStringOrigin);
            Assert.Equal("Databse=Foo", contextInfo.ConnectionString);
            Assert.Equal("SomeName", contextInfo.ConnectionStringName);
            Assert.Equal("My.Provider", contextInfo.ConnectionProviderName);
        }
        public void DbContextInfo_can_provide_a_code_first_model_without_hitting_the_database_when_also_give_config()
        {
            Database.SetInitializer<CodeFirstScaffoldingContextWithConnection>(null);

            using (var context = new DbContextInfo(
                typeof(CodeFirstScaffoldingContextWithConnection),
                AddConnectionStrings(CreateEmptyConfig()),
                new DbProviderInfo("System.Data.SqlClient", "2008")).CreateInstance())
            {
                // Will throw if CodeFirstConnectionString is not found and will throw if it is used to
                // make a connection since it points to a server that does not exist.
                var objectContext = ((IObjectContextAdapter)context).ObjectContext;
                Assert.Equal("CodeFirstScaffoldingContextWithConnection", objectContext.DefaultContainerName);
                Assert.Equal("Bar", ((CodeFirstScaffoldingContextWithConnection)context).ExtraInfo);
            }
        }
        public void CreateInstance_should_use_passed_provider_info_when_building_model_even_when_config_is_passed_as_well()
        {
            var config = AddConnectionStrings(
                CreateEmptyConfig().AddDefaultConnectionFactory(
                    typeof(FakeDbContextInfoConnectionFactory).FullName + ", 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 Should_obtain_DefaultConnectionFactory_from_supplied_config_but_this_can_be_overriden()
        {
            RunTestWithConnectionFactory(
                Database.ResetDefaultConnectionFactory,
                () =>
            {
                var config = CreateEmptyConfig().AddDefaultConnectionFactory(
                    typeof(FakeDbContextInfoConnectionFactory).FullName + ", EntityFramework.UnitTests",
                    new string[0]);

                var contextInfo = new DbContextInfo(typeof(ContextWithoutDefaultCtor), config);

                Assert.IsType <FakeDbContextInfoConnectionFactory>(FunctionalTestsConfiguration.OriginalConnectionFactories.Last());

                Assert.Equal(DbConnectionStringOrigin.Convention, contextInfo.ConnectionStringOrigin);
                Assert.Equal(@"Data Source=.\SQLEXPRESS;Initial Catalog=foo;Integrated Security=True", contextInfo.ConnectionString);
                Assert.Equal("System.Data.SqlClient", contextInfo.ConnectionProviderName);
            });
        }
        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);
            }
        }
        public void Should_use_connectioin_string_from_supplied_config_even_if_DefaultConnectionFactory_is_also_present()
        {
            RunTestWithConnectionFactory(
                Database.ResetDefaultConnectionFactory,
                () =>
            {
                var config =
                    AddConnectionStrings(
                        CreateEmptyConfig().AddDefaultConnectionFactory(
                            typeof(FakeDbContextInfoConnectionFactory).FullName + ", EntityFramework.UnitTests",
                            new string[0]));

                var contextInfo = new DbContextInfo(typeof(ContextWithoutDefaultCtor), config);

                Assert.Equal(DbConnectionStringOrigin.Configuration, contextInfo.ConnectionStringOrigin);
                Assert.Equal("Initial Catalog=foo", contextInfo.ConnectionString);
                Assert.Equal("foo", contextInfo.ConnectionStringName);
                Assert.Equal("System.Data.SqlClient", contextInfo.ConnectionProviderName);
            });
        }
Exemplo n.º 34
0
        [Fact] // CodePlex 291, 1316
        public void CreateInstance_should_not_cause_database_initializer_to_run_even_if_context_consturctor_would_cause_it()
        {
            var contextInfo = new DbContextInfo(typeof(InitTestContext));

            using (var context = contextInfo.CreateInstance())
            {
                // Do something that would normally cause initialization
                Assert.NotNull(((IObjectContextAdapter)context).ObjectContext);
            }

            Assert.False(InitTestInitializer.HasRun);

            // Use context normally--initializer should now run.
            using (var context = new InitTestContext())
            {
                Assert.NotNull(((IObjectContextAdapter)context).ObjectContext);
            }

            Assert.True(InitTestInitializer.HasRun);
        }
        public void Should_use_DefaultConnectionFactory_set_in_code_even_if_one_was_supplied_in_config()
        {
#pragma warning disable 612,618
            RunTestWithConnectionFactory(
                () => Database.DefaultConnectionFactory = new SqlConnectionFactory(),
                () =>
#pragma warning restore 612,618
            {
                var config = CreateEmptyConfig().
                             AddDefaultConnectionFactory(
                    typeof(FakeDbContextInfoConnectionFactory).FullName + ", EntityFramework.UnitTests",
                    new string[0]);

                var contextInfo = new DbContextInfo(typeof(ContextWithoutDefaultCtor), config);

                Assert.Equal(DbConnectionStringOrigin.Convention, contextInfo.ConnectionStringOrigin);
                Assert.True(contextInfo.ConnectionString.Contains(@"Data Source=.\SQLEXPRESS"));
                Assert.True(contextInfo.ConnectionString.Contains(@"Initial Catalog=foo"));
                Assert.Equal("System.Data.SqlClient", contextInfo.ConnectionProviderName);
            });
        }
        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);
        }
Exemplo n.º 37
0
        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();
                }
            }
        }
Exemplo n.º 38
0
        internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, bool calledByCreateDatabase)
            : base(null)
        {
            Check.NotNull(configuration, "configuration");
            Check.NotNull(configuration.ContextType, "configuration.ContextType");

            _configuration = configuration;
            _calledByCreateDatabase = calledByCreateDatabase;
            _existenceState = existenceState;

            if (usersContext != null)
            {
                _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();
            _usersContext = context;

            try
            {
                _migrationAssembly
                    = new MigrationAssembly(
                        _configuration.MigrationsAssembly,
                        _configuration.MigrationsNamespace);

                _currentModel = context.GetModel();

                _connection = context.Database.Connection;

                _providerFactory = DbProviderServices.GetProviderFactory(_connection);

                _defaultSchema
                    = context.InternalContext.DefaultSchema
                      ?? EdmModelExtensions.DefaultSchema;

                _historyContextFactory
                    = _configuration
                        .GetHistoryContextFactory(_usersContextInfo.ConnectionProviderName);

                _historyRepository
                    = new HistoryRepository(
                        context.InternalContext,
                        _usersContextInfo.ConnectionString,
                        _providerFactory,
                        _configuration.ContextKey,
                        _configuration.CommandTimeout,
                        _historyContextFactory,
                        schemas: new[] { _defaultSchema }.Concat(GetHistorySchemas()),
                        contextForInterception: _usersContext,
                        initialExistence: _existenceState);

                _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()));

                var interceptionContext = new DbInterceptionContext();
                interceptionContext = interceptionContext.WithDbContext(_usersContext);

                _targetDatabase
                    = Strings.LoggingTargetDatabaseFormat(
                        DbInterception.Dispatch.Connection.GetDataSource(_connection, interceptionContext),
                        DbInterception.Dispatch.Connection.GetDatabase(_connection, interceptionContext),
                        _usersContextInfo.ConnectionProviderName,
                        _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo
                            ? Strings.LoggingExplicit
                            : _usersContextInfo.ConnectionStringOrigin.ToString());

                _legacyContextKey = context.InternalContext.DefaultContextKey;
                _emptyModel = GetEmptyModel();
            }
            finally
            {
                if (usersContext == null)
                {
                    _usersContext = null;
                    context.Dispose();
                }
            }
        }
Exemplo n.º 39
0
        internal static void MapContextToInfo(Type contextType, DbContextInfo info)
        {
            DebugCheck.NotNull(contextType);
            DebugCheck.NotNull(info);

            _infoMapping.AddOrUpdate(contextType, info, (t, i) => info);
        }
        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);
            }
        }
Exemplo n.º 41
0
        internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext)
            : base(null)
        {
            Contract.Requires(configuration != null);
            Contract.Requires(configuration.ContextType != null);

            _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);

                _defaultSchema = context.InternalContext.DefaultSchema;

                var historySchemas = GetHistorySchemas();

                if (!string.IsNullOrWhiteSpace(_defaultSchema))
                {
                    historySchemas = historySchemas.Concat(new[] { _defaultSchema });
                }

                _historyRepository
                    = new HistoryRepository(_usersContextInfo.ConnectionString, _providerFactory, historySchemas);

                _providerManifestToken
                    = context.InternalContext.ModelProviderInfo != null
                          ? context.InternalContext.ModelProviderInfo.ProviderManifestToken
                          : DbProviderServices.GetProviderServices(connection).
                                GetProviderManifestTokenChecked(connection);
                _targetDatabase
                    = Strings.LoggingTargetDatabaseFormat(
                        connection.DataSource,
                        connection.Database,
                        _usersContextInfo.ConnectionProviderName,
                        _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo
                            ? Strings.LoggingExplicit
                            : _usersContextInfo.ConnectionStringOrigin.ToString());
            }
            finally
            {
                if (usersContext == null)
                {
                    context.Dispose();
                }
            }

            var providerInfo
                = new DbProviderInfo(_usersContextInfo.ConnectionProviderName, _providerManifestToken);

            _emptyModel = new Lazy<XDocument>(() => new DbModelBuilder().Build(providerInfo).GetModel());

            _historyRepository.AppendHistoryModel(_currentModel, providerInfo);
        }
        public void ContextType_should_return_tyoe_of_passed_context_instance()
        {
            var contextInfo = new DbContextInfo(new SimpleContext());

            Assert.Same(typeof(SimpleContext), contextInfo.ContextType);
        }
Exemplo n.º 43
0
        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();
                }
            }
        }