示例#1
0
        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 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;
        }
        public LazyInternalConnection(DbConnectionInfo connectionInfo)
        {
            //Contract.Requires(connectionInfo != null);

            _connectionInfo = connectionInfo;
            AppConfig = AppConfig.DefaultInstance;
        }
        public LazyInternalConnection(DbContext context, DbConnectionInfo connectionInfo)
            : base(new DbInterceptionContext().WithDbContext(context))
        {
            DebugCheck.NotNull(connectionInfo);

            _connectionInfo = connectionInfo;
            AppConfig = AppConfig.DefaultInstance;
        }
        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 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);
        }
        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);
        }
        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();
        }
示例#10
0
        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();
            }
        }
示例#11
0
        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);
            }
        }
示例#12
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(contextType, null, new AppConfig(config), connectionInfo)
 {
     //Contract.Requires(contextType != null);
     //Contract.Requires(config != null);
     //Contract.Requires(connectionInfo != 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);
            }
        }
示例#14
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 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);
        }
        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);
            }
        }
示例#17
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"))
 {
 }
示例#18
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;
        }
示例#19
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;
                    }
                }
            }
        }
示例#20
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(contextType, null, AppConfig.DefaultInstance, connectionInfo)
 {
     //Contract.Requires(contextType != null);
     //Contract.Requires(connectionInfo != null);
 }
        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;
        }
示例#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;
        }
示例#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;
                    }
                }
            }
        }
示例#24
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;
        }
示例#25
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"))
 {
 }
示例#26
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)
        {
            //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;
        }