public LazyInternalConnection(DbConnectionInfo connectionInfo)
        {
            //Contract.Requires(connectionInfo != null);

            _connectionInfo = connectionInfo;
            AppConfig = AppConfig.DefaultInstance;
        }
 public void GetConnectionString_throws_when_cant_find_named_connection_in_config()
 {
     var config = new AppConfig(CreateEmptyConfig());
     var info = new DbConnectionInfo("FindMe");
     Assert.Equal(Strings.DbConnectionInfo_ConnectionStringNotFound("FindMe"),
                  Assert.Throws<InvalidOperationException>(() => info.GetConnectionString(config)).Message);
 }
        public LazyInternalConnection(DbConnectionInfo connectionInfo)
        {
            DebugCheck.NotNull(connectionInfo);

            _connectionInfo = connectionInfo;
            AppConfig = AppConfig.DefaultInstance;
        }
        static void Main(string[] args)
        {
            //  Parse arguments
            var parameters = ParseArguments(args);
            if (parameters == null) return;

            //  Generate the script
            var connection = new DbConnectionInfo(parameters.connection);

            var tool = new ToolingFacade(
                migrationsAssemblyName: parameters.migrationsAssembly,
                contextAssemblyName: parameters.contextAssembly,
                configurationTypeName: parameters.configurationTypeName,
                workingDirectory:      null,
                configurationFilePath: parameters.config,
                dataDirectory:         null,
                connectionStringInfo:  connection
            );

            var script = tool.ScriptUpdate(parameters.source, parameters.target, force: true);

            //  Output the script
            if (parameters.output == null) Console.WriteLine(script);
            else
            {
                Directory.CreateDirectory(Path.GetDirectoryName(parameters.output));
                File.WriteAllText(parameters.output, script);
            }
        }
        public LazyInternalConnection(DbContext context, DbConnectionInfo connectionInfo)
            : base(new DbInterceptionContext().WithDbContext(context))
        {
            DebugCheck.NotNull(connectionInfo);

            _connectionInfo = connectionInfo;
            AppConfig = AppConfig.DefaultInstance;
        }
        public void GetConnectionString_throws_when_cant_find_named_connection_in_config()
        {
            var config = new AppConfig(CreateEmptyConfig());
            var info   = new DbConnectionInfo("FindMe");

            Assert.Equal(
                Strings.DbConnectionInfo_ConnectionStringNotFound("FindMe"),
                Assert.Throws <InvalidOperationException>(() => info.GetConnectionString(config)).Message);
        }
        public void Exceptions_applying_new_connection_surfaced()
        {
            var connection = new DbConnectionInfo("GetMeFromSuppliedConfig");

            Assert.Equal(
                Strings.DbContext_ConnectionStringNotFound("GetMeFromSuppliedConfig"),
                Assert.Throws <InvalidOperationException>(
                    () => new DbContextInfo(typeof(ContextWithConnectionNameNotInAppConfigFile), CreateEmptyConfig(), connection)).Message);
        }
        public void Returns_valid_connection_from_string_and_provider()
        {
            var config     = new AppConfig(CreateEmptyConfig());
            var info       = new DbConnectionInfo("connection_string", "provider_invariant_name");
            var connection = info.GetConnectionString(config);

            Assert.Null(connection.Name);
            Assert.Equal("connection_string", connection.ConnectionString);
            Assert.Equal("provider_invariant_name", connection.ProviderName);
        }
        public void Returns_valid_connection_from_string_and_provider()
        {
            var config = new AppConfig(CreateEmptyConfig());
            var info = new DbConnectionInfo("connection_string", "provider_invariant_name");
            var connection = info.GetConnectionString(config);

            Assert.Null(connection.Name);
            Assert.Equal("connection_string", connection.ConnectionString);
            Assert.Equal("provider_invariant_name", connection.ProviderName);
        }
        public void Can_find_named_connection_in_config()
        {
            var config = new AppConfig(CreateEmptyConfig().AddConnectionString("FindMe", "connection_string", "provider_invariant_name"));
            var info = new DbConnectionInfo("FindMe");
            var connection = info.GetConnectionString(config);

            Assert.Equal("FindMe", connection.Name);
            Assert.Equal("connection_string", connection.ConnectionString);
            Assert.Equal("provider_invariant_name", connection.ProviderName);
        }
        public void Can_find_named_connection_in_config()
        {
            var config     = new AppConfig(CreateEmptyConfig().AddConnectionString("FindMe", "connection_string", "provider_invariant_name"));
            var info       = new DbConnectionInfo("FindMe");
            var connection = info.GetConnectionString(config);

            Assert.Equal("FindMe", connection.Name);
            Assert.Equal("connection_string", connection.ConnectionString);
            Assert.Equal("provider_invariant_name", connection.ProviderName);
        }
        private DbMigrator GetMigrator(string configurationType, DbConnectionInfo targetDatabase)
        {
            var configuration = (DbMigrationsConfiguration)AssemblyUnderTest.CreateInstance(configurationType);
            if (configuration == null)
            {
                throw new ArgumentException(
                    $"Failed to create an instance of {configurationType} using assembly {AssemblyUnderTest}.",
                    nameof(configurationType));
            }

            configuration.TargetDatabase = targetDatabase;
            return new DbMigrator(configuration);
        }
Exemple #13
0
        internal DbContextInfo(DbContext context, Func <IDbDependencyResolver> resolver = null)
        {
            Check.NotNull <DbContext>(context, nameof(context));
            this._resolver    = resolver ?? (Func <IDbDependencyResolver>)(() => DbConfiguration.DependencyResolver);
            this._contextType = context.GetType();
            this._appConfig   = AppConfig.DefaultInstance;
            InternalContext internalContext = context.InternalContext;

            this._connectionProviderName = internalContext.ProviderName;
            this._connectionInfo         = new DbConnectionInfo(internalContext.OriginalConnectionString, this._connectionProviderName);
            this._connectionString       = internalContext.OriginalConnectionString;
            this._connectionStringName   = internalContext.ConnectionStringName;
            this._connectionStringOrigin = internalContext.ConnectionStringOrigin;
        }
        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 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_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);
            }
        }
Exemple #17
0
        /// <summary>
        ///     Called internally when a context info is needed for an existing context, which may not be constructable.
        /// </summary>
        /// <param name="context"> The context instance to get info from. </param>
        internal DbContextInfo(DbContext context)
        {
            Check.NotNull(context, "context");

            _contextType = context.GetType();
            _appConfig   = AppConfig.DefaultInstance;

            var internalContext = context.InternalContext;

            _connectionProviderName = internalContext.ProviderName;

            _connectionInfo = new DbConnectionInfo(internalContext.OriginalConnectionString, _connectionProviderName);

            _connectionString       = internalContext.OriginalConnectionString;
            _connectionStringName   = internalContext.ConnectionStringName;
            _connectionStringOrigin = internalContext.ConnectionStringOrigin;
        }
        private static void MigrateUsingDbMigrator()
        {
            var connectionInfo = new DbConnectionInfo("MigrationDemo");
            var configuration = new Configuration();
            configuration.TargetDatabase = connectionInfo;

            var migrator = new DbMigrator(configuration);

            Console.WriteLine("Before Migration");
            PrintMigrationStatus(migrator);

            migrator.Update();

            Console.WriteLine("After Migration");
            PrintMigrationStatus(migrator);
            PrintSeededData();
        }
        public void CreateFromScratch()
        {
            var connectionString = "Data Source=localhost\\sqlexpress;Initial Catalog=Session_" + Guid.NewGuid().ToString() + ";Trusted_Connection=True;";
            try
            {
                var dbConnection = new DbConnectionInfo(connectionString, "System.Data.SqlClient");
                var settings = new Model.Migrations.Configuration();
                settings.TargetDatabase = dbConnection;
                var migrator = new DbMigrator(settings);

                migrator.Update(targetMigration: "201307170913098_AddedUserIsDeletedField");
            }
            finally
            {
                var context = new ConferenceContext(connectionString);
                context.Database.Delete();
            }
        }
Exemple #20
0
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException("contextType");
            }

            _contextType       = contextType;
            _modelProviderInfo = modelProviderInfo;
            _appConfig         = config;
            _connectionInfo    = connectionInfo;

            _activator = CreateActivator();

            if (_activator != null)
            {
                DatabaseInitializerSuppressor.Instance.Suppress(_contextType);

                var context = _activator();

                if (context != null)
                {
                    context.InternalContext.OnDisposing += (_, __) => DatabaseInitializerSuppressor.Instance.Unsuppress(_contextType);

                    _isConstructible = true;

                    PushConfiguration(context);

                    using (context)
                    {
                        ConfigureContext(context);

                        _connectionString       = context.InternalContext.Connection.ConnectionString;
                        _connectionStringName   = context.InternalContext.ConnectionStringName;
                        _connectionProviderName = context.InternalContext.ProviderName;
                        _connectionStringOrigin = context.InternalContext.ConnectionStringOrigin;
                    }
                }
            }
        }
        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);
            }
        }
Exemple #22
0
        // <summary>
        // Called internally when a context info is needed for an existing context, which may not be constructable.
        // </summary>
        // <param name="context"> The context instance to get info from. </param>
        internal DbContextInfo(DbContext context, Func <IDbDependencyResolver> resolver = null)
        {
            Check.NotNull(context, "context");

            _resolver = resolver ?? (() => DbConfiguration.DependencyResolver);

            _contextType = context.GetType();
            _appConfig   = AppConfig.DefaultInstance;

            var internalContext = context.InternalContext;

            _connectionProviderName = internalContext.ProviderName;

            _connectionInfo = new DbConnectionInfo(internalContext.OriginalConnectionString, _connectionProviderName);

            _connectionString       = internalContext.OriginalConnectionString;
            _connectionStringName   = internalContext.ConnectionStringName;
            _connectionStringOrigin = internalContext.ConnectionStringOrigin;
        }
Exemple #23
0
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo,
            Func <IDbDependencyResolver> resolver = null)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException("contextType");
            }

            _resolver = resolver ?? (() => DbConfiguration.DependencyResolver);

            _contextType       = contextType;
            _modelProviderInfo = modelProviderInfo;
            _appConfig         = config;
            _connectionInfo    = connectionInfo;

            _activator = CreateActivator();

            if (_activator != null)
            {
                var context = CreateInstance();

                if (context != null)
                {
                    _isConstructible = true;

                    using (context)
                    {
                        _connectionString =
                            DbInterception.Dispatch.Connection.GetConnectionString(
                                context.InternalContext.Connection,
                                new DbInterceptionContext().WithDbContext(context));
                        _connectionStringName   = context.InternalContext.ConnectionStringName;
                        _connectionProviderName = context.InternalContext.ProviderName;
                        _connectionStringOrigin = context.InternalContext.ConnectionStringOrigin;
                    }
                }
            }
        }
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException("contextType");
            }

            _contextType       = contextType;
            _modelProviderInfo = modelProviderInfo;
            _appConfig         = config;
            _connectionInfo    = connectionInfo;

            _activator = CreateActivator();

            if (_activator != null)
            {
                var context = _activator();

                if (context != null)
                {
                    _isConstructible = true;

                    PushConfiguration(context);

                    using (context)
                    {
                        ConfigureContext(context);

                        _connectionString       = context.InternalContext.Connection.ConnectionString;
                        _connectionStringName   = context.InternalContext.ConnectionStringName;
                        _connectionProviderName = context.InternalContext.ProviderName;
                        _connectionStringOrigin = context.InternalContext.ConnectionStringOrigin;
                    }
                }
            }
        }
        public ToolingFacade(
            string migrationsAssemblyName,
            string contextAssemblyName,
            string configurationTypeName,
            string workingDirectory,
            string configurationFilePath,
            string dataDirectory,
            DbConnectionInfo connectionStringInfo)
        {
            Check.NotEmpty(migrationsAssemblyName, "migrationsAssemblyName");

            _migrationsAssemblyName = migrationsAssemblyName;
            _contextAssemblyName = contextAssemblyName;
            _configurationTypeName = configurationTypeName;
            _connectionStringInfo = connectionStringInfo;

            var info = new AppDomainSetup
                {
                    ShadowCopyFiles = "true"
                };

            if (!string.IsNullOrWhiteSpace(workingDirectory))
            {
                info.ApplicationBase = workingDirectory;
            }

            _configurationFile = new ConfigurationFileUpdater().Update(configurationFilePath);
            info.ConfigurationFile = _configurationFile;

            var friendlyName = "MigrationsToolingFacade" + Convert.ToBase64String(Guid.NewGuid().ToByteArray());

            _appDomain = AppDomain.CreateDomain(friendlyName, null, info);

            if (!string.IsNullOrWhiteSpace(dataDirectory))
            {
                _appDomain.SetData("DataDirectory", dataDirectory);
            }
        }
Exemple #26
0
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo,
            Func <IDbDependencyResolver> resolver = null)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException(nameof(contextType));
            }
            this._resolver          = resolver ?? (Func <IDbDependencyResolver>)(() => DbConfiguration.DependencyResolver);
            this._contextType       = contextType;
            this._modelProviderInfo = modelProviderInfo;
            this._appConfig         = config;
            this._connectionInfo    = connectionInfo;
            this._activator         = this.CreateActivator();
            if (this._activator == null)
            {
                return;
            }
            DbContext instance = this.CreateInstance();

            if (instance == null)
            {
                return;
            }
            this._isConstructible = true;
            using (instance)
            {
                this._connectionString       = DbInterception.Dispatch.Connection.GetConnectionString(instance.InternalContext.Connection, new DbInterceptionContext().WithDbContext(instance));
                this._connectionStringName   = instance.InternalContext.ConnectionStringName;
                this._connectionProviderName = instance.InternalContext.ProviderName;
                this._connectionStringOrigin = instance.InternalContext.ConnectionStringOrigin;
            }
        }
        private DbMigrator GetDbMigrator(Assembly assembly, string configurationType, DbConnectionInfo targetDatabase = null)
        {
            var targetAssemblyConfig = (DbMigrationsConfiguration)assembly.CreateInstance(configurationType);

            if (targetAssemblyConfig == null)
            {
                Log.Warning("The assembly at the path {assemblyPath} does not contain " +
                            "the migration configuration type {configType}. This may be due to a " +
                            "migration from or to a version where that config type doesn't exist. " +
                            "A target migration of '0' will be used, which will rollback all migrations.", assembly.CodeBase, configurationType);
            }
            else
            {
                if (targetDatabase != null)
                {
                    targetAssemblyConfig.TargetDatabase = targetDatabase;
                }
                else
                {
                    //Force local db to allow for meta data resolution
                    //We can probably get rid of this by implementing: 
                    //http://stackoverflow.com/questions/4741499/how-to-configure-providermanifesttoken-for-ef-code-first
                    targetAssemblyConfig.TargetDatabase = m_ConnectionInfoBuilder.Build(new DatabaseEndpoint()
                    {
                        ServerName = @"(localdb)\mssqllocaldb"
                    }, AuthenticationMode.Integrated);
                }
            }

            return targetAssemblyConfig != null ? new DbMigrator(targetAssemblyConfig) : null;
        }
Exemple #28
0
 /// <summary>
 /// Creates a new instance representing a given <see cref="DbContext" />, targeting a specific database.
 /// An external config object (e.g. app.config or web.config) can be supplied and will be used during connection string
 /// resolution. This includes looking for connection strings and DefaultConnectionFactory entries.
 /// </summary>
 /// <param name="contextType">
 /// The type deriving from <see cref="DbContext" />.
 /// </param>
 /// <param name="config"> An object representing the config file. </param>
 /// <param name="connectionInfo"> Connection information for the database to be used. </param>
 public DbContextInfo(Type contextType, Configuration config, DbConnectionInfo connectionInfo)
     : this(
         Check.NotNull(contextType, "contextType"), null, new AppConfig(Check.NotNull(config, "config")),
         Check.NotNull(connectionInfo, "connectionInfo"))
 {
 }
Exemple #29
0
 /// <summary>
 /// Creates a new instance representing a given <see cref="T:System.Data.Entity.DbContext" />, targeting a specific database.
 /// An external config object (e.g. app.config or web.config) can be supplied and will be used during connection string
 /// resolution. This includes looking for connection strings and DefaultConnectionFactory entries.
 /// </summary>
 /// <param name="contextType">
 /// The type deriving from <see cref="T:System.Data.Entity.DbContext" />.
 /// </param>
 /// <param name="config"> An object representing the config file. </param>
 /// <param name="connectionInfo"> Connection information for the database to be used. </param>
 public DbContextInfo(Type contextType, System.Configuration.Configuration config, DbConnectionInfo connectionInfo)
     : this(Check.NotNull <Type>(contextType, nameof(contextType)), (DbProviderInfo)null, new AppConfig(Check.NotNull <System.Configuration.Configuration>(config, nameof(config))), Check.NotNull <DbConnectionInfo>(connectionInfo, nameof(connectionInfo)), (Func <IDbDependencyResolver>)null)
 {
 }
        public void AssertEachPendingUpwardMigration(string configurationType, DbConnectionInfo targetDatabase)
        {
            var migrator = GetMigrator(configurationType, targetDatabase);
            var migrationsToApply = migrator
                .GetPendingMigrations()
                .OrderBy(migrationId => migrationId);

            var expectedMigrations = new List<string>(migrator
                .GetDatabaseMigrations()
                .OrderBy(migrationId => migrationId));

            foreach (var migrationId in migrationsToApply)
            {
                ApplyMigration(migrator, migrationId);

                expectedMigrations.Add(migrationId);
                var actualMigrations = migrator.GetDatabaseMigrations().OrderBy(actualId => actualId);

                AssertDatabaseMigrationsAreEqual(migrationId, expectedMigrations, actualMigrations);
            }
        }
 /// <summary>
 ///     Creates a new instance representing a given <see cref = "DbContext" />, targeting a specific database.
 ///     An external config object (e.g. app.config or web.config) can be supplied and will be used during connection string
 ///     resolution. This includes looking for connection strings and DefaultConnectionFactory entries.
 /// </summary>
 /// <param name = "contextType">The type deriving from <see cref = "DbContext" />.</param>
 /// <param name = "config">An object representing the config file.</param>
 /// <param name="connectionInfo">Connection information for the database to be used.</param>
 public DbContextInfo(Type contextType, Configuration config, DbConnectionInfo connectionInfo)
     : this(contextType, null, new AppConfig(config), connectionInfo)
 {
     //Contract.Requires(contextType != null);
     //Contract.Requires(config != null);
     //Contract.Requires(connectionInfo != null);
 }
Exemple #32
0
        private ToolingFacade CreateFacade()
        {
            DbConnectionInfo connectionStringInfo = null;

            if (!string.IsNullOrWhiteSpace(_arguments.ConnectionStringName))
            {
                Contract.Assert(string.IsNullOrWhiteSpace(_arguments.ConnectionString));
                Contract.Assert(string.IsNullOrWhiteSpace(_arguments.ConnectionProviderName));

                connectionStringInfo = new DbConnectionInfo(_arguments.ConnectionStringName);
            }
            else if (!string.IsNullOrWhiteSpace(_arguments.ConnectionString))
            {
                Contract.Assert(string.IsNullOrWhiteSpace(_arguments.ConnectionStringName));
                Contract.Assert(!string.IsNullOrWhiteSpace(_arguments.ConnectionProviderName));

                connectionStringInfo = new DbConnectionInfo(
                    _arguments.ConnectionString, _arguments.ConnectionProviderName);
            }

            var facade
                = new ToolingFacade(
                    _arguments.AssemblyName,
                    _arguments.ConfigurationTypeName,
                    _arguments.WorkingDirectory,
                    _arguments.ConfigurationFile,
                    _arguments.DataDirectory,
                    connectionStringInfo);

            facade.LogInfoDelegate = WriteLine;
            facade.LogWarningDelegate = WriteWarning;

            if (_arguments.Verbose)
            {
                facade.LogVerboseDelegate = sql => WriteVerbose(Strings.VerboseMessage(sql));
            }

            return facade;
        }
Exemple #33
0
        // <summary>
        // Called internally when a context info is needed for an existing context, which may not be constructable.
        // </summary>
        // <param name="context"> The context instance to get info from. </param>
        internal DbContextInfo(DbContext context, Func<IDbDependencyResolver> resolver = null)
        {
            Check.NotNull(context, "context");

            _resolver = resolver ?? (() => DbConfiguration.DependencyResolver);

            _contextType = context.GetType();
            _appConfig = AppConfig.DefaultInstance;

            var internalContext = context.InternalContext;
            _connectionProviderName = internalContext.ProviderName;

            _connectionInfo = new DbConnectionInfo(internalContext.OriginalConnectionString, _connectionProviderName);

            _connectionString = internalContext.OriginalConnectionString;
            _connectionStringName = internalContext.ConnectionStringName;
            _connectionStringOrigin = internalContext.ConnectionStringOrigin;
        }
        public void AssertEachPossibleDownwardMigration(string configurationType, DbConnectionInfo targetDatabase)
        {
            var migrator = GetMigrator(configurationType, targetDatabase);
            var currentMigrationId = migrator
                .GetDatabaseMigrations()
                .OrderBy(migrationId => migrationId)
                .LastOrDefault();

            var migrationsToApply = migrator
                .GetLocalMigrations()
                .OrderByDescending(migrationId => migrationId)
                .SkipWhile(migrationId =>
                    string.Compare(migrationId, currentMigrationId, StringComparison.OrdinalIgnoreCase) >= 0
                )
                .ToList();

            var expectedMigrations = new List<string>(migrationsToApply);

            // this will test migrating to before InitialCreate
            migrationsToApply.Add("0");

            foreach (var migrationId in migrationsToApply)
            {
                ApplyMigration(migrator, migrationId);

                var actualMigrations = migrator.GetDatabaseMigrations().OrderByDescending(actualId => actualId);

                AssertDatabaseMigrationsAreEqual(migrationId, expectedMigrations, actualMigrations);

                expectedMigrations.Remove(migrationId);
            }
        }
Exemple #35
0
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException("contextType");
            }

            _contextType = contextType;
            _modelProviderInfo = modelProviderInfo;
            _appConfig = config;
            _connectionInfo = connectionInfo;

            _activator = CreateActivator();

            if (_activator != null)
            {
                var context = _activator();

                if (context != null)
                {
                    _isConstructible = true;

                    PushConfiguration(context);

                    using (context)
                    {
                        ConfigureContext(context);

                        _connectionString = context.InternalContext.Connection.ConnectionString;
                        _connectionStringName = context.InternalContext.ConnectionStringName;
                        _connectionProviderName = context.InternalContext.ProviderName;
                        _connectionStringOrigin = context.InternalContext.ConnectionStringOrigin;
                    }
                }
            }
        }
Exemple #36
0
 /// <summary>
 ///     Creates a new instance representing a given <see cref="DbContext" /> targeting a specific database.
 /// </summary>
 /// <param name="contextType">
 ///     The type deriving from <see cref="DbContext" /> .
 /// </param>
 /// <param name="connectionInfo"> Connection information for the database to be used. </param>
 public DbContextInfo(Type contextType, DbConnectionInfo connectionInfo)
     : this(
         Check.NotNull(contextType, "contextType"), null, AppConfig.DefaultInstance, Check.NotNull(connectionInfo, "connectionInfo"))
 {
 }
Exemple #37
0
        /// <summary>
        ///     Called internally when a context info is needed for an existing context, which may not be constructable.
        /// </summary>
        /// <param name="context"> The context instance to get info from. </param>
        internal DbContextInfo(DbContext context)
        {
            Check.NotNull(context, "context");

            _contextType = context.GetType();
            _appConfig = AppConfig.DefaultInstance;

            var internalContext = context.InternalContext;
            _connectionProviderName = internalContext.ProviderName;

            _connectionInfo = new DbConnectionInfo(internalContext.OriginalConnectionString, _connectionProviderName);

            _connectionString = internalContext.OriginalConnectionString;
            _connectionStringName = internalContext.ConnectionStringName;
            _connectionStringOrigin = internalContext.ConnectionStringOrigin;
        }
Exemple #38
0
 /// <summary>
 ///     Creates a new instance representing a given <see cref="DbContext" />, targeting a specific database.
 ///     An external config object (e.g. app.config or web.config) can be supplied and will be used during connection string
 ///     resolution. This includes looking for connection strings and DefaultConnectionFactory entries.
 /// </summary>
 /// <param name="contextType">
 ///     The type deriving from <see cref="DbContext" /> .
 /// </param>
 /// <param name="config"> An object representing the config file. </param>
 /// <param name="connectionInfo"> Connection information for the database to be used. </param>
 public DbContextInfo(Type contextType, Configuration config, DbConnectionInfo connectionInfo)
     : this(
         Check.NotNull(contextType, "contextType"), null, new AppConfig(Check.NotNull(config, "config")),
         Check.NotNull(connectionInfo, "connectionInfo"))
 {
 }
Exemple #39
0
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo,
            Func<IDbDependencyResolver> resolver = null)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException("contextType");
            }

            _resolver = resolver ?? (() => DbConfiguration.DependencyResolver);

            _contextType = contextType;
            _modelProviderInfo = modelProviderInfo;
            _appConfig = config;
            _connectionInfo = connectionInfo;

            _activator = CreateActivator();

            if (_activator != null)
            {
                var context = CreateInstance();

                if (context != null)
                {
                    _isConstructible = true;

                    using (context)
                    {
                        _connectionString = 
                            DbInterception.Dispatch.Connection.GetConnectionString(
                            context.InternalContext.Connection,
                            new DbInterceptionContext().WithDbContext(context));
                        _connectionStringName = context.InternalContext.ConnectionStringName;
                        _connectionProviderName = context.InternalContext.ProviderName;
                        _connectionStringOrigin = context.InternalContext.ConnectionStringOrigin;
                    }
                }
            }
        }
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException("contextType");
            }

            _contextType = contextType;
            _modelProviderInfo = modelProviderInfo;
            _appConfig = config;
            _connectionInfo = connectionInfo;

            _activator = CreateActivator();

            if (_activator != null)
            {
                DatabaseInitializerSuppressor.Instance.Suppress(_contextType);

                var context = _activator();

                if (context != null)
                {
                    context.InternalContext.OnDisposing += (_, __) => DatabaseInitializerSuppressor.Instance.Unsuppress(_contextType);

                    _isConstructible = true;

                    PushConfiguration(context);

                    using (context)
                    {
                        ConfigureContext(context);

                        _connectionString = context.InternalContext.Connection.ConnectionString;
                        _connectionStringName = context.InternalContext.ConnectionStringName;
                        _connectionProviderName = context.InternalContext.ProviderName;
                        _connectionStringOrigin = context.InternalContext.ConnectionStringOrigin;
                    }
                }
            }
        }
        public void AssertMigration(string targetMigrationId, string configurationType, DbConnectionInfo targetDatabase)
        {
            var migrator = GetMigrator(configurationType, targetDatabase);
            ApplyMigration(migrator, targetMigrationId);

            var expectedMigrations = migrator
                .GetLocalMigrations()
                .OrderBy(migrationId => migrationId)
                .TakeWhile(migrationId =>
                    string.Compare(migrationId, targetMigrationId, StringComparison.OrdinalIgnoreCase) < 1
                );

            var actualMigrations = migrator
                .GetDatabaseMigrations()
                .OrderBy(migrationId => migrationId);

            AssertDatabaseMigrationsAreEqual(targetMigrationId, expectedMigrations, actualMigrations);
        }
Exemple #42
0
 /// <summary>
 /// Creates a new instance representing a given <see cref="DbContext" /> targeting a specific database.
 /// </summary>
 /// <param name="contextType">
 /// The type deriving from <see cref="DbContext" />.
 /// </param>
 /// <param name="connectionInfo"> Connection information for the database to be used. </param>
 public DbContextInfo(Type contextType, DbConnectionInfo connectionInfo)
     : this(
         Check.NotNull(contextType, "contextType"), null, AppConfig.DefaultInstance, Check.NotNull(connectionInfo, "connectionInfo"))
 {
 }
Exemple #43
0
 /// <summary>
 /// Creates a new instance representing a given <see cref="T:System.Data.Entity.DbContext" /> targeting a specific database.
 /// </summary>
 /// <param name="contextType">
 /// The type deriving from <see cref="T:System.Data.Entity.DbContext" />.
 /// </param>
 /// <param name="connectionInfo"> Connection information for the database to be used. </param>
 public DbContextInfo(Type contextType, DbConnectionInfo connectionInfo)
     : this(Check.NotNull <Type>(contextType, nameof(contextType)), (DbProviderInfo)null, AppConfig.DefaultInstance, Check.NotNull <DbConnectionInfo>(connectionInfo, nameof(connectionInfo)), (Func <IDbDependencyResolver>)null)
 {
 }
        /// <summary>
        /// Called internally when a context info is needed for an existing context, which may not be constructable.
        /// </summary>
        /// <param name="context">The context instance to get info from.</param>
        internal DbContextInfo(DbContext context)
        {
            //Contract.Requires(context != null);

            _contextType = context.GetType();
            _appConfig = AppConfig.DefaultInstance;

            var internalContext = context.InternalContext;
            _connectionProviderName = internalContext.ProviderName;

            _connectionInfo = new DbConnectionInfo(internalContext.OriginalConnectionString, _connectionProviderName);

            _connectionString = internalContext.OriginalConnectionString;
            _connectionStringName = internalContext.ConnectionStringName;
            _connectionStringOrigin = internalContext.ConnectionStringOrigin;
        }
 /// <summary>
 ///     Creates a new instance representing a given <see cref = "DbContext" /> targeting a specific database.
 /// </summary>
 /// <param name = "contextType">The type deriving from <see cref = "DbContext" />.</param>
 /// <param name="connectionInfo">Connection information for the database to be used.</param>
 public DbContextInfo(Type contextType, DbConnectionInfo connectionInfo)
     : this(contextType, null, AppConfig.DefaultInstance, connectionInfo)
 {
     //Contract.Requires(contextType != null);
     //Contract.Requires(connectionInfo != null);
 }