protected RelationalConnection([NotNull] IDbContextOptions options, [NotNull] ILoggerFactory loggerFactory)
        {
            Check.NotNull(options, nameof(options));
            Check.NotNull(loggerFactory, nameof(loggerFactory));

            _logger = new LazyRef<ILogger>(loggerFactory.CreateLogger<RelationalConnection>);

            var storeConfig = RelationalOptionsExtension.Extract(options);

            _commandTimeout = storeConfig.CommandTimeout;

            if (storeConfig.Connection != null)
            {
                if (!string.IsNullOrWhiteSpace(storeConfig.ConnectionString))
                {
                    throw new InvalidOperationException(Strings.ConnectionAndConnectionString);
                }

                _connection = new LazyRef<DbConnection>(() => storeConfig.Connection);
                _connectionOwned = false;
                _openedCount = storeConfig.Connection.State == ConnectionState.Open ? 1 : 0;
            }
            else if (!string.IsNullOrWhiteSpace(storeConfig.ConnectionString))
            {
                _connectionString = storeConfig.ConnectionString;
                _connection = new LazyRef<DbConnection>(CreateDbConnection);
                _connectionOwned = true;
            }
            else
            {
                throw new InvalidOperationException(Strings.NoConnectionOrConnectionString);
            }
        }
        protected RelationalConnection(
            [NotNull] DbContextConfiguration configuration,
            [NotNull] ConnectionStringResolver connectionStringResolver)
        {
            Check.NotNull(configuration, "configuration");
            Check.NotNull(connectionStringResolver, "connectionStringResolver");

            _connectionStringResolver = connectionStringResolver;

            var storeConfig = RelationalOptionsExtension.Extract(configuration);

            if (storeConfig.Connection != null)
            {
                if (!string.IsNullOrWhiteSpace(storeConfig.ConnectionString))
                {
                    throw new InvalidOperationException(Strings.FormatConnectionAndConnectionString());
                }

                _connection = new LazyRef<DbConnection>(() => storeConfig.Connection);
                _connectionOwned = false;
                _openedCount = storeConfig.Connection.State == ConnectionState.Open ? 1 : 0;
            }
            else if (!string.IsNullOrWhiteSpace(storeConfig.ConnectionString))
            {
                _connectionString = _connectionStringResolver.Resolve(storeConfig.ConnectionString);
                _connection = new LazyRef<DbConnection>(CreateDbConnection);
                _connectionOwned = true;
            }
            else
            {
                throw new InvalidOperationException(Strings.FormatNoConnectionOrConnectionString());
            }
        }
        public ColumnModification(
            [NotNull] InternalEntityEntry entry,
            [NotNull] IProperty property,
            [NotNull] IRelationalPropertyAnnotations propertyAnnotations,
            [NotNull] ParameterNameGenerator parameterNameGenerator,
            bool isRead,
            bool isWrite,
            bool isKey,
            bool isCondition)
        {
            Check.NotNull(entry, nameof(entry));
            Check.NotNull(property, nameof(property));
            Check.NotNull(propertyAnnotations, nameof(propertyAnnotations));
            Check.NotNull(parameterNameGenerator, nameof(parameterNameGenerator));

            Entry = entry;
            Property = property;
            ColumnName = propertyAnnotations.ColumnName;

            _parameterName = isWrite
                ? new LazyRef<string>(parameterNameGenerator.GenerateNext)
                : new LazyRef<string>((string)null);
            _originalParameterName = isCondition
                ? new LazyRef<string>(parameterNameGenerator.GenerateNext)
                : new LazyRef<string>((string)null);
            _outputParameterName = isRead
                ? new LazyRef<string>(parameterNameGenerator.GenerateNext)
                : new LazyRef<string>((string)null);

            IsRead = isRead;
            IsWrite = isWrite;
            IsKey = isKey;
            IsCondition = isCondition;
        }
Exemplo n.º 4
0
        public void Has_value_is_true_if_constructed_with_value()
        {
            var lazy = new LazyRef<string>((string)null);

            Assert.True(lazy.HasValue);
            Assert.Null(lazy.Value);
        }
        protected RelationalConnection([NotNull] IDbContextOptions options, [NotNull] ILogger logger)
        {
            Check.NotNull(options, nameof(options));
            Check.NotNull(logger, nameof(logger));

            _logger = logger;

            var relationalOptions = RelationalOptionsExtension.Extract(options);

            _commandTimeout = relationalOptions.CommandTimeout;

            if (relationalOptions.Connection != null)
            {
                if (!string.IsNullOrWhiteSpace(relationalOptions.ConnectionString))
                {
                    throw new InvalidOperationException(RelationalStrings.ConnectionAndConnectionString);
                }

                _connection = new LazyRef<DbConnection>(() => relationalOptions.Connection);
                _connectionOwned = false;
            }
            else if (!string.IsNullOrWhiteSpace(relationalOptions.ConnectionString))
            {
                _connectionString = relationalOptions.ConnectionString;
                _connection = new LazyRef<DbConnection>(CreateDbConnection);
                _connectionOwned = true;
            }
            else
            {
                throw new InvalidOperationException(RelationalStrings.NoConnectionOrConnectionString);
            }

            _throwOnAmbientTransaction = relationalOptions.ThrowOnAmbientTransaction ?? true;
        }
Exemplo n.º 6
0
        public MigrationAssembly([NotNull] DbContext context, [NotNull] IDbContextOptions options)
        {
            Check.NotNull(context, nameof(context));
            Check.NotNull(options, nameof(options));

            var contextType = context.GetType();

            var assemblyName = RelationalOptionsExtension.Extract(options)?.MigrationsAssembly;
            var assembly = assemblyName == null
                ? contextType.GetTypeInfo().Assembly
                : Assembly.Load(new AssemblyName(assemblyName));

            _migrations = new LazyRef<IReadOnlyList<Migration>>(
                () => GetMigrationTypes(assembly)
                    .Where(t => TryGetContextType(t) == contextType)
                    .Select(t => (Migration)Activator.CreateInstance(t.AsType()))
                    .OrderBy(m => m.Id)
                    .ToList());
            _modelSnapshot = new LazyRef<ModelSnapshot>(
                () => (
                    from t in GetTypes(assembly)
                    where t.IsSubclassOf(typeof(ModelSnapshot))
                          && TryGetContextType(t) == contextType
                    select (ModelSnapshot)Activator.CreateInstance(t.AsType()))
                    .FirstOrDefault());
        }
Exemplo n.º 7
0
        public Migrator(
            [NotNull] IMigrationsAssembly migrationAssembly,
            [NotNull] IHistoryRepository historyRepository,
            [NotNull] IDatabaseCreator databaseCreator,
            [NotNull] IMigrationsSqlGenerator sqlGenerator,
            [NotNull] ISqlStatementExecutor executor,
            [NotNull] IRelationalConnection connection,
            [NotNull] IUpdateSqlGenerator sql,
            [NotNull] ILoggerFactory loggerFactory)
        {
            Check.NotNull(migrationAssembly, nameof(migrationAssembly));
            Check.NotNull(historyRepository, nameof(historyRepository));
            Check.NotNull(databaseCreator, nameof(databaseCreator));
            Check.NotNull(sqlGenerator, nameof(sqlGenerator));
            Check.NotNull(executor, nameof(executor));
            Check.NotNull(connection, nameof(connection));
            Check.NotNull(sql, nameof(sql));
            Check.NotNull(loggerFactory, nameof(loggerFactory));

            _migrationAssembly = migrationAssembly;
            _historyRepository = historyRepository;
            _databaseCreator = (IRelationalDatabaseCreator)databaseCreator;
            _sqlGenerator = sqlGenerator;
            _executor = executor;
            _connection = connection;
            _sql = sql;
            _logger = new LazyRef<ILogger>(loggerFactory.CreateLogger<Migrator>);
        }
        public MigrationsAssembly(
            [NotNull] DbContext context,
            [NotNull] IDbContextOptions options,
            [NotNull] IMigrationsIdGenerator idGenerator)
        {
            Check.NotNull(context, nameof(context));
            Check.NotNull(options, nameof(options));
            Check.NotNull(idGenerator, nameof(idGenerator));

            var contextType = context.GetType();

            var assemblyName = RelationalOptionsExtension.Extract(options)?.MigrationsAssembly;
            var assembly = assemblyName == null
                ? contextType.GetTypeInfo().Assembly
                : Assembly.Load(new AssemblyName(assemblyName));

            _idGenerator = idGenerator;
            _migrations = new LazyRef<IReadOnlyDictionary<string, TypeInfo>>(
                () => (
                        from t in assembly.GetConstructibleTypes()
                        where t.IsSubclassOf(typeof(Migration))
                            && t.GetCustomAttribute<DbContextAttribute>()?.ContextType == contextType
                        let id = t.GetCustomAttribute<MigrationAttribute>()?.Id
                        orderby id
                        select new { Key = id, Element = t })
                    .ToDictionary(i => i.Key, i => i.Element));
            _modelSnapshot = new LazyRef<ModelSnapshot>(
                () => (
                        from t in assembly.GetConstructibleTypes()
                        where t.IsSubclassOf(typeof(ModelSnapshot))
                              && t.GetCustomAttribute<DbContextAttribute>()?.ContextType == contextType
                        select (ModelSnapshot)Activator.CreateInstance(t.AsType()))
                    .FirstOrDefault());
        }
        public MigrationsOperations(
            [NotNull] ILoggerProvider loggerProvider,
            [NotNull] string assemblyName,
            [NotNull] string startupAssemblyName,
            [NotNull] string projectDir,
            [NotNull] string rootNamespace,
            [CanBeNull] IServiceProvider dnxServices = null)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotEmpty(assemblyName, nameof(assemblyName));
            Check.NotEmpty(startupAssemblyName, nameof(startupAssemblyName));
            Check.NotNull(projectDir, nameof(projectDir));
            Check.NotNull(rootNamespace, nameof(rootNamespace));

            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(loggerProvider);

            _loggerProvider = loggerProvider;
            _logger = new LazyRef<ILogger>(() => loggerFactory.CreateCommandsLogger());
            _projectDir = projectDir;
            _rootNamespace = rootNamespace;
            _servicesBuilder = new DesignTimeServicesBuilder(dnxServices);
            _contextOperations = new DbContextOperations(
                loggerProvider,
                assemblyName,
                startupAssemblyName,
                dnxServices);
        }
        public MigrationScaffolder(
            [NotNull] DbContext context,
            [NotNull] IModel model,
            [NotNull] IMigrationAssembly migrationAssembly,
            [NotNull] IModelDiffer modelDiffer,
            [NotNull] IMigrationIdGenerator idGenerator,
            [NotNull] MigrationCodeGenerator migrationCodeGenerator,
            [NotNull] IHistoryRepository historyRepository,
            [NotNull] ILoggerFactory loggerFactory,
            [NotNull] IMigrationModelFactory modelFactory)
        {
            Check.NotNull(context, nameof(context));
            Check.NotNull(model, nameof(model));
            Check.NotNull(migrationAssembly, nameof(migrationAssembly));
            Check.NotNull(modelDiffer, nameof(modelDiffer));
            Check.NotNull(idGenerator, nameof(idGenerator));
            Check.NotNull(migrationCodeGenerator, nameof(migrationCodeGenerator));
            Check.NotNull(historyRepository, nameof(historyRepository));
            Check.NotNull(loggerFactory, nameof(loggerFactory));
            Check.NotNull(modelFactory, nameof(modelFactory));

            _contextType = context.GetType();
            _model = model;
            _migrationAssembly = migrationAssembly;
            _modelDiffer = modelDiffer;
            _idGenerator = idGenerator;
            _migrationCodeGenerator = migrationCodeGenerator;
            _historyRepository = historyRepository;
            _logger = new LazyRef<ILogger>(loggerFactory.CreateLogger<MigrationScaffolder>);
            _modelFactory = modelFactory;
        }
        public MigrationsScaffolder(
            [NotNull] DbContext context,
            [NotNull] IModel model,
            [NotNull] IMigrationsAssembly migrationsAssembly,
            [NotNull] IMigrationsModelDiffer modelDiffer,
            [NotNull] IMigrationsIdGenerator idGenerator,
            [NotNull] MigrationsCodeGenerator migrationCodeGenerator,
            [NotNull] IHistoryRepository historyRepository,
            [NotNull] ILoggerFactory loggerFactory,
            [NotNull] IDatabaseProviderServices providerServices)
        {
            Check.NotNull(context, nameof(context));
            Check.NotNull(model, nameof(model));
            Check.NotNull(migrationsAssembly, nameof(migrationsAssembly));
            Check.NotNull(modelDiffer, nameof(modelDiffer));
            Check.NotNull(idGenerator, nameof(idGenerator));
            Check.NotNull(migrationCodeGenerator, nameof(migrationCodeGenerator));
            Check.NotNull(historyRepository, nameof(historyRepository));
            Check.NotNull(loggerFactory, nameof(loggerFactory));
            Check.NotNull(providerServices, nameof(providerServices));

            _contextType = context.GetType();
            _model = model;
            _migrationsAssembly = migrationsAssembly;
            _modelDiffer = modelDiffer;
            _idGenerator = idGenerator;
            _migrationCodeGenerator = migrationCodeGenerator;
            _historyRepository = historyRepository;
            _logger = new LazyRef<ILogger>(() => loggerFactory.CreateCommandsLogger());
            _activeProvider = providerServices.InvariantName;
        }
        public MigrationsAssembly(
            [NotNull] DbContext context,
            [NotNull] IDbContextOptions options,
            [NotNull] IMigrationsIdGenerator idGenerator)
        {
            Check.NotNull(context, nameof(context));
            Check.NotNull(options, nameof(options));
            Check.NotNull(idGenerator, nameof(idGenerator));

            var contextType = context.GetType();

            var assemblyName = RelationalOptionsExtension.Extract(options)?.MigrationsAssembly;
            var assembly = assemblyName == null
                ? contextType.GetTypeInfo().Assembly
                : Assembly.Load(new AssemblyName(assemblyName));

            _idGenerator = idGenerator;
            _migrations = new LazyRef<IReadOnlyList<Migration>>(
                () => assembly.GetConstructibleTypes()
                    .Where(t => typeof(Migration).IsAssignableFrom(t.AsType())
                        && t.GetCustomAttribute<DbContextAttribute>()?.ContextType == contextType)
                    .Select(t => (Migration)Activator.CreateInstance(t.AsType()))
                    .OrderBy(m => m.Id)
                    .ToList());
            _modelSnapshot = new LazyRef<ModelSnapshot>(
                () => (
                        from t in assembly.GetConstructibleTypes()
                        where t.IsSubclassOf(typeof(ModelSnapshot))
                              && t.GetCustomAttribute<DbContextAttribute>()?.ContextType == contextType
                        select (ModelSnapshot)Activator.CreateInstance(t.AsType()))
                    .FirstOrDefault());
        }
        public virtual DbContextConfiguration Initialize(
            [NotNull] IServiceProvider externalProvider,
            [NotNull] IServiceProvider scopedProvider,
            [NotNull] DbContextOptions contextOptions,
            [NotNull] DbContext context,
            ServiceProviderSource serviceProviderSource)
        {
            Check.NotNull(externalProvider, "externalProvider");
            Check.NotNull(scopedProvider, "scopedProvider");
            Check.NotNull(contextOptions, "contextOptions");
            Check.NotNull(context, "context");
            Check.IsDefined(serviceProviderSource, "serviceProviderSource");

            _externalProvider = externalProvider;
            _services = new ContextServices(scopedProvider);
            _serviceProviderSource = serviceProviderSource;
            _contextOptions = contextOptions;
            _context = context;
            _dataStoreServices = new LazyRef<DataStoreServices>(() => _services.DataStoreSelector.SelectDataStore(this));
            _modelFromSource = new LazyRef<IModel>(() => _services.ModelSource.GetModel(_context, _dataStoreServices.Value.ModelBuilderFactory));
            _dataStore = new LazyRef<DataStore>(() => _dataStoreServices.Value.Store);
            _connection = new LazyRef<DataStoreConnection>(() => _dataStoreServices.Value.Connection);
            _loggerFactory = new LazyRef<ILoggerFactory>(() => _externalProvider.TryGetService<ILoggerFactory>() ?? new NullLoggerFactory());
            _database = new LazyRef<Database>(() => _dataStoreServices.Value.Database);
            _stateManager = new LazyRef<StateManager>(() => _services.StateManager);

            return this;
        }
Exemplo n.º 14
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public StartupInvoker(
            [NotNull] LazyRef<ILogger> logger,
            [NotNull] Assembly startupAssembly,
            [CanBeNull] string environment,
            [NotNull] string contentRootPath)
        {
            Check.NotNull(logger, nameof(logger));
            Check.NotNull(startupAssembly, nameof(startupAssembly));
            Check.NotEmpty(contentRootPath, nameof(contentRootPath));

            _logger = logger;

            _environment = !string.IsNullOrEmpty(environment)
                ? environment
                : "Development";

            _contentRootPath = contentRootPath;

            _startupAssemblyName = startupAssembly.GetName().Name;

            _startupType = startupAssembly.GetLoadableDefinedTypes().Where(t => typeof(IStartup).IsAssignableFrom(t.AsType()))
                .Concat(startupAssembly.GetLoadableDefinedTypes().Where(t => t.Name == "Startup" + _environment))
                .Concat(startupAssembly.GetLoadableDefinedTypes().Where(t => t.Name == "Startup"))
                .Concat(startupAssembly.GetLoadableDefinedTypes().Where(t => t.Name == "Program"))
                .Concat(startupAssembly.GetLoadableDefinedTypes().Where(t => t.Name == "App"))
                .Select(t => t.AsType())
                .FirstOrDefault();
        }
Exemplo n.º 15
0
        public OperationExecutor(
            [NotNull] CommonOptions options,
            [CanBeNull] string environment)
        {
            var projectFile = Path.Combine(Directory.GetCurrentDirectory(), Project.FileName);
            var project = ProjectReader.GetProject(projectFile);

            var projectConfiguration = options.Configuration ?? Constants.DefaultConfiguration;
            var projectFramework = options.Framework;

            var projectContext = ProjectContext.Create(project.ProjectFilePath,
                projectFramework,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            var runtimeOutputPath = projectContext.GetOutputPaths(projectConfiguration)?.RuntimeOutputPath;
            if (!string.IsNullOrEmpty(runtimeOutputPath))
            {
                Reporter.Verbose.WriteLine(
                    ToolsCliStrings.LogDataDirectory(runtimeOutputPath));
                Environment.SetEnvironmentVariable(DataDirEnvName, runtimeOutputPath);
#if NET451
                AppDomain.CurrentDomain.SetData("DataDirectory", runtimeOutputPath);
#endif
            }

            var assemblyName = project.GetCompilerOptions(projectFramework, projectConfiguration).OutputName;
            var projectDir = project.ProjectDirectory;
            var rootNamespace = project.Name;

            var assemblyLoader = new AssemblyLoader(Assembly.Load);
            var projectAssembly = assemblyLoader.Load(assemblyName);

            _contextOperations = new LazyRef<DbContextOperations>(
                          () => new DbContextOperations(
                              new LoggerProvider(name => new ConsoleCommandLogger(name)),
                              projectAssembly,
                              projectAssembly,
                              environment,
                              projectDir));
            _databaseOperations = new LazyRef<DatabaseOperations>(
                () => new DatabaseOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    assemblyLoader,
                    projectAssembly,
                    environment,
                    projectDir,
                    projectDir,
                    rootNamespace));
            _migrationsOperations = new LazyRef<MigrationsOperations>(
                () => new MigrationsOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    projectAssembly,
                    assemblyLoader,
                    projectAssembly,
                    environment,
                    projectDir,
                    projectDir,
                    rootNamespace));
        }
Exemplo n.º 16
0
        public void Has_value_is_false_until_value_accessed()
        {
            var lazy = new LazyRef<string>(() => "Cherry Coke");

            Assert.False(lazy.HasValue);
            Assert.Equal("Cherry Coke", lazy.Value);
            Assert.True(lazy.HasValue);
        }
Exemplo n.º 17
0
        public void Value_can_be_set_explicitly()
        {
            var lazy = new LazyRef<string>(() => "Cherry Coke");

            lazy.Value = "Fresca";

            Assert.True(lazy.HasValue);
            Assert.Equal("Fresca", lazy.Value);
        }
Exemplo n.º 18
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="DbUpdateException" /> class.
        /// </summary>
        /// <param name="message"> The error message that explains the reason for the exception. </param>
        /// <param name="entries"> The entries that were involved in the error. </param>
        /// <param name="innerException"> The exception that is the cause of the current exception. </param>
        public DbUpdateException(
            [NotNull] string message,
            [CanBeNull] Exception innerException,
            [NotNull] IReadOnlyList<IUpdateEntry> entries)
            : base(message, innerException)
        {
            Check.NotEmpty(entries, nameof(entries));

            _entries = new LazyRef<IReadOnlyList<EntityEntry>>(() => entries.Select(e => e.ToEntityEntry()).ToList());
        }
Exemplo n.º 19
0
        protected ModelSnapshot()
        {
            _model = new LazyRef<IModel>(
                () =>
                {
                    var modelBuilder = new ModelBuilder(new ConventionSet());
                    BuildModel(modelBuilder);

                    return modelBuilder.Model;
                });
        }
        protected MigrationsFixtureBase()
        {
            _services = new LazyRef<IServiceProvider>(
                () =>
                {
                    var services = new ServiceCollection();
                    ConfigureServices(services);

                    return services.BuildServiceProvider();
                });
        }
Exemplo n.º 21
0
        public void Initialization_can_be_reset()
        {
            var lazy = new LazyRef<string>(() => "Cherry Coke");

            Assert.Equal("Cherry Coke", lazy.Value);

            lazy.Reset(() => "Fresca");

            Assert.False(lazy.HasValue);
            Assert.Equal("Fresca", lazy.Value);
            Assert.True(lazy.HasValue);
        }
Exemplo n.º 22
0
        public MigrationTool([NotNull] ILoggerProvider loggerProvider, [NotNull] Assembly assembly)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotNull(assembly, nameof(assembly));

            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(loggerProvider);

            _loggerProvider = loggerProvider;
            _logger = new LazyRef<ILogger>(() => loggerFactory.CreateLogger<MigrationTool>());
            _assembly = assembly;
        }
Exemplo n.º 23
0
        public BatchExecutor(
            [NotNull] IRelationalTypeMapper typeMapper,
            [NotNull] DbContext context,
            [NotNull] ILoggerFactory loggerFactory)
        {
            Check.NotNull(typeMapper, nameof(typeMapper));
            Check.NotNull(context, nameof(context));
            Check.NotNull(loggerFactory, nameof(loggerFactory));

            _typeMapper = typeMapper;
            _context = context;
            _logger = new LazyRef<ILogger>(() => (loggerFactory.CreateLogger<BatchExecutor>()));
        }
Exemplo n.º 24
0
        protected Migration()
        {
            _targetModel = new LazyRef<IModel>(
                () =>
                    {
                        var modelBuilder = new ModelBuilder(new ConventionSet());
                        BuildTargetModel(modelBuilder);

                        return modelBuilder.Model;
                    });
            _upOperations = new LazyRef<List<MigrationOperation>>(() => BuildOperations(Up));
            _downOperations = new LazyRef<List<MigrationOperation>>(() => BuildOperations(Down));
        }
Exemplo n.º 25
0
        public DatabaseTool(
            [CanBeNull] IServiceProvider serviceProvider,
            [NotNull] ILoggerProvider loggerProvider)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));

            _serviceProvider = new ServiceProvider(serviceProvider);
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(loggerProvider);
            _logger = new LazyRef<ILogger>(() => loggerFactory.CreateLogger<DatabaseTool>());
            _serviceProvider.AddService(typeof(ILogger), _logger.Value);
            _serviceProvider.AddService(typeof(CSharpCodeGeneratorHelper), new CSharpCodeGeneratorHelper());
            _serviceProvider.AddService(typeof(ModelUtilities), new ModelUtilities());
        }
Exemplo n.º 26
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual bool Clear()
        {
            lock (_lock)
            {
                if (!_tables.HasValue)
                {
                    return(false);
                }

                _tables = CreateTables();

                return(true);
            }
        }
Exemplo n.º 27
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected HistoryRepository(
            [NotNull] IDatabaseCreator databaseCreator,
            [NotNull] IRawSqlCommandBuilder rawSqlCommandBuilder,
            [NotNull] IRelationalConnection connection,
            [NotNull] IDbContextOptions options,
            [NotNull] IMigrationsModelDiffer modelDiffer,
            [NotNull] IMigrationsSqlGenerator migrationsSqlGenerator,
            [NotNull] IRelationalAnnotationProvider annotations,
            [NotNull] ISqlGenerationHelper sqlGenerationHelper)
        {
            Check.NotNull(databaseCreator, nameof(databaseCreator));
            Check.NotNull(rawSqlCommandBuilder, nameof(rawSqlCommandBuilder));
            Check.NotNull(connection, nameof(connection));
            Check.NotNull(options, nameof(options));
            Check.NotNull(modelDiffer, nameof(modelDiffer));
            Check.NotNull(migrationsSqlGenerator, nameof(migrationsSqlGenerator));
            Check.NotNull(annotations, nameof(annotations));
            Check.NotNull(sqlGenerationHelper, nameof(sqlGenerationHelper));

            _databaseCreator        = (IRelationalDatabaseCreator)databaseCreator;
            _rawSqlCommandBuilder   = rawSqlCommandBuilder;
            _connection             = connection;
            _modelDiffer            = modelDiffer;
            _migrationsSqlGenerator = migrationsSqlGenerator;
            SqlGenerationHelper     = sqlGenerationHelper;

            var relationalOptions = RelationalOptionsExtension.Extract(options);

            TableName   = relationalOptions?.MigrationsHistoryTableName ?? DefaultTableName;
            TableSchema = relationalOptions?.MigrationsHistoryTableSchema;
            _model      = new LazyRef <IModel>(
                () =>
            {
                var modelBuilder = new ModelBuilder(new ConventionSet());
                modelBuilder.Entity <HistoryRow>(
                    x =>
                {
                    ConfigureTable(x);
                    x.ToTable(TableName, TableSchema);
                });

                return(modelBuilder.Model);
            });
            var entityType = new LazyRef <IEntityType>(() => _model.Value.FindEntityType(typeof(HistoryRow)));

            _migrationIdColumnName = new LazyRef <string>(
                () => annotations.For(entityType.Value.FindProperty(nameof(HistoryRow.MigrationId))).ColumnName);
            _productVersionColumnName = new LazyRef <string>(
                () => annotations.For(entityType.Value.FindProperty(nameof(HistoryRow.ProductVersion))).ColumnName);
        }
Exemplo n.º 28
0
        public DatabaseTool(
            [CanBeNull] IServiceProvider serviceProvider,
            [NotNull] ILoggerProvider loggerProvider)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));

            _serviceProvider = new ServiceProvider(serviceProvider);
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);
            _logger = new LazyRef <ILogger>(() => loggerFactory.CreateLogger <DatabaseTool>());
            _serviceProvider.AddService(typeof(ILogger), _logger.Value);
            _serviceProvider.AddService(typeof(CSharpCodeGeneratorHelper), new CSharpCodeGeneratorHelper());
            _serviceProvider.AddService(typeof(ModelUtilities), new ModelUtilities());
        }
Exemplo n.º 29
0
        public HistoryRepository(
            [NotNull] IDatabaseCreator databaseCreator,
            [NotNull] ISqlStatementExecutor executor,
            [NotNull] IRelationalConnection connection,
            [NotNull] IDbContextOptions options,
            [NotNull] IMigrationsModelDiffer modelDiffer,
            [NotNull] IMigrationsSqlGenerator migrationsSqlGenerator,
            [NotNull] IRelationalAnnotationProvider annotations,
            [NotNull] ISqlGenerator sqlGenerator)
        {
            Check.NotNull(databaseCreator, nameof(databaseCreator));
            Check.NotNull(executor, nameof(executor));
            Check.NotNull(connection, nameof(connection));
            Check.NotNull(options, nameof(options));
            Check.NotNull(modelDiffer, nameof(modelDiffer));
            Check.NotNull(migrationsSqlGenerator, nameof(migrationsSqlGenerator));
            Check.NotNull(annotations, nameof(annotations));
            Check.NotNull(sqlGenerator, nameof(sqlGenerator));

            _databaseCreator = (IRelationalDatabaseCreator)databaseCreator;
            _executor = executor;
            _connection = connection;
            _modelDiffer = modelDiffer;
            _migrationsSqlGenerator = migrationsSqlGenerator;
            SqlGenerator = sqlGenerator;

            var relationalOptions = RelationalOptionsExtension.Extract(options);
            TableName = relationalOptions?.MigrationsHistoryTableName ?? DefaultTableName;
            TableSchema = relationalOptions.MigrationsHistoryTableSchema;
            _model = new LazyRef<IModel>(
                () =>
                {
                    var modelBuilder = new ModelBuilder(new ConventionSet());
                    modelBuilder.Entity<HistoryRow>(
                        x =>
                        {
                            ConfigureTable(x);
                            x.ToTable(TableName, TableSchema);
                        });

                    return modelBuilder.Model;
                });
            var entityType = new LazyRef<IEntityType>(() => _model.Value.GetEntityType(typeof(HistoryRow)));
            _migrationIdColumnName = new LazyRef<string>(
                () => annotations.For(entityType.Value.FindProperty(nameof(HistoryRow.MigrationId))).ColumnName);
            _productVersionColumnName = new LazyRef<string>(
                () => annotations.For(entityType.Value.FindProperty(nameof(HistoryRow.ProductVersion))).ColumnName);
        }
Exemplo n.º 30
0
        protected Database(
            [NotNull] DbContextService <IModel> model,
            [NotNull] DataStoreCreator dataStoreCreator,
            [NotNull] DataStoreConnection connection,
            [NotNull] ILoggerFactory loggerFactory)
        {
            Check.NotNull(model, "model");
            Check.NotNull(dataStoreCreator, "dataStoreCreator");
            Check.NotNull(connection, "connection");
            Check.NotNull(loggerFactory, "loggerFactory");

            _model            = model;
            _dataStoreCreator = dataStoreCreator;
            _connection       = connection;
            _logger           = new LazyRef <ILogger>(loggerFactory.Create <Database>);
        }
Exemplo n.º 31
0
        public DbContextOperations(
            [NotNull] ILoggerProvider loggerProvider,
            [NotNull] string assemblyName,
            [NotNull] string startupAssemblyName,
            [CanBeNull] IServiceProvider dnxServices = null)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotEmpty(assemblyName, nameof(assemblyName));
            Check.NotEmpty(startupAssemblyName, nameof(startupAssemblyName));

            _loggerProvider      = loggerProvider;
            _assemblyName        = assemblyName;
            _startupAssemblyName = startupAssemblyName;
            _dnxServices         = dnxServices;
            _logger = new LazyRef <ILogger>(() => _loggerProvider.CreateCommandsLogger());
        }
Exemplo n.º 32
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used 
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual IDbContextServices Initialize(
            IServiceProvider scopedProvider,
            IDbContextOptions contextOptions,
            DbContext context)
        {
            _scopedProvider = scopedProvider;
            _contextOptions = contextOptions;
            _currentContext = new CurrentDbContext(context);

            _providerServices = new LazyRef<IDatabaseProviderServices>(() =>
                _scopedProvider.GetRequiredService<IDatabaseProviderSelector>().SelectServices());

            _modelFromSource = new LazyRef<IModel>(CreateModel);

            return this;
        }
Exemplo n.º 33
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public RelationalQueryContext(
            [NotNull] Func <IQueryBuffer> queryBufferFactory,
            [NotNull] IRelationalConnection connection,
            [NotNull] LazyRef <IStateManager> stateManager,
            [NotNull] IConcurrencyDetector concurrencyDetector,
            [NotNull] IExecutionStrategyFactory executionStrategyFactory)
            : base(
                Check.NotNull(queryBufferFactory, nameof(queryBufferFactory)),
                Check.NotNull(stateManager, nameof(stateManager)),
                Check.NotNull(concurrencyDetector, nameof(concurrencyDetector)))
        {
            Check.NotNull(connection, nameof(connection));

            Connection = connection;
            ExecutionStrategyFactory = executionStrategyFactory;
        }
Exemplo n.º 34
0
        public MigrationTool(
            [NotNull] ILoggerProvider loggerProvider,
            [NotNull] Assembly assembly,
            [CanBeNull] IServiceProvider services = null)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotNull(assembly, nameof(assembly));

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);

            _loggerProvider = loggerProvider;
            _logger         = new LazyRef <ILogger>(() => loggerFactory.CreateLogger <MigrationTool>());
            _assembly       = assembly;
            _services       = services;
        }
        public DbContextOperations(
            [NotNull] ILoggerProvider loggerProvider,
            [NotNull] string assemblyName,
            [NotNull] string startupAssemblyName,
            [CanBeNull] string environment)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotEmpty(assemblyName, nameof(assemblyName));
            Check.NotEmpty(startupAssemblyName, nameof(startupAssemblyName));

            _loggerProvider = loggerProvider;
            _assemblyName = assemblyName;
            _startupAssemblyName = startupAssemblyName;
            _logger = new LazyRef<ILogger>(() => _loggerProvider.CreateCommandsLogger());

            var startup = new StartupInvoker(startupAssemblyName, environment);
            _runtimeServices = startup.ConfigureServices();
        }
Exemplo n.º 36
0
        protected DataStore(
            [NotNull] IModel model,
            [NotNull] IEntityKeyFactorySource entityKeyFactorySource,
            [NotNull] IEntityMaterializerSource entityMaterializerSource,
            [NotNull] ILoggerFactory loggerFactory)
        {
            Check.NotNull(model, nameof(model));
            Check.NotNull(entityKeyFactorySource, nameof(entityKeyFactorySource));
            Check.NotNull(entityMaterializerSource, nameof(entityMaterializerSource));
            Check.NotNull(loggerFactory, nameof(loggerFactory));

            Model = model;

            EntityKeyFactorySource   = entityKeyFactorySource;
            EntityMaterializerSource = entityMaterializerSource;

            _logger = new LazyRef <ILogger>(loggerFactory.CreateLogger <DataStore>);
        }
Exemplo n.º 37
0
        public DbContextOperations(
            [NotNull] ILoggerProvider loggerProvider,
            [NotNull] string assemblyName,
            [NotNull] string startupAssemblyName,
            [CanBeNull] string environment)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotEmpty(assemblyName, nameof(assemblyName));
            Check.NotEmpty(startupAssemblyName, nameof(startupAssemblyName));

            _loggerProvider      = loggerProvider;
            _assemblyName        = assemblyName;
            _startupAssemblyName = startupAssemblyName;
            _logger = new LazyRef <ILogger>(() => _loggerProvider.CreateCommandsLogger());

            var startup = new StartupInvoker(startupAssemblyName, environment);

            _runtimeServices = startup.ConfigureServices();
        }
Exemplo n.º 38
0
        public DatabaseTool(
            [CanBeNull] IServiceProvider serviceProvider,
            [NotNull] ILoggerProvider loggerProvider)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));

            _serviceProvider = new ServiceProvider(serviceProvider);
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(loggerProvider);
            _logger = new LazyRef<ILogger>(() => loggerFactory.CreateLogger<DatabaseTool>());
            _serviceProvider.AddService(typeof(ILogger), _logger.Value);
            _serviceProvider.AddService(typeof(IFileService), new FileSystemFileService());
            _serviceProvider.AddService(typeof(CSharpCodeGeneratorHelper), new CSharpCodeGeneratorHelper());
            _serviceProvider.AddService(typeof(ModelUtilities), new ModelUtilities());
            var metadataReferencesProvider = new MetadataReferencesProvider(_serviceProvider);
            _serviceProvider.AddService(typeof(MetadataReferencesProvider), metadataReferencesProvider);
            var compilationService = new RoslynCompilationService();
            _serviceProvider.AddService(typeof(ITemplating), new RazorTemplating(compilationService, metadataReferencesProvider));
        }
Exemplo n.º 39
0
        protected RelationalConnection([NotNull] DbContextConfiguration configuration)
        {
            Check.NotNull(configuration, "configuration");

            var storeConfigs = configuration.ContextOptions.Extensions
                               .OfType <RelationalConfigurationExtension>()
                               .ToArray();

            if (storeConfigs.Length == 0)
            {
                throw new InvalidOperationException(Strings.FormatNoDataStoreConfigured());
            }

            if (storeConfigs.Length > 1)
            {
                throw new InvalidOperationException(Strings.FormatMultipleDataStoresConfigured());
            }

            var storeConfig = storeConfigs[0];

            if (storeConfig.Connection != null)
            {
                if (!string.IsNullOrWhiteSpace(storeConfig.ConnectionString))
                {
                    throw new InvalidOperationException(Strings.FormatConnectionAndConnectionString());
                }

                _connection      = new LazyRef <DbConnection>(() => storeConfig.Connection);
                _connectionOwned = false;
                _openedCount     = storeConfig.Connection.State == ConnectionState.Open ? 1 : 0;
            }
            else if (!string.IsNullOrWhiteSpace(storeConfig.ConnectionString))
            {
                _connectionString = storeConfig.ConnectionString;
                _connection       = new LazyRef <DbConnection>(CreateDbConnection);
                _connectionOwned  = true;
            }
            else
            {
                throw new InvalidOperationException(Strings.FormatNoConnectionOrConnectionString());
            }
        }
Exemplo n.º 40
0
        public Program([NotNull] IServiceProvider dnxServices)
        {
            Check.NotNull(dnxServices, nameof(dnxServices));

            var appEnv     = dnxServices.GetRequiredService <IApplicationEnvironment>();
            var runtimeEnv = dnxServices.GetRequiredService <IRuntimeEnvironment>();

            _applicationShutdown = dnxServices.GetRequiredService <IApplicationShutdown>();
            _useConsoleColors    = runtimeEnv.OperatingSystem == "Windows";

            var loggerProvider = new LoggerProvider(name => new ConsoleCommandLogger(name, verbose: true));

            _logger = new LazyRef <ILogger>(() => loggerProvider.CreateCommandsLogger());

            var targetName        = appEnv.ApplicationName;
            var startupTargetName = appEnv.ApplicationName;
            var projectDir        = appEnv.ApplicationBasePath;
            var rootNamespace     = appEnv.ApplicationName;

            _contextOperations = new LazyRef <DbContextOperations>(
                () => new DbContextOperations(
                    loggerProvider,
                    targetName,
                    startupTargetName,
                    dnxServices));
            _databaseOperations = new LazyRef <DatabaseOperations>(
                () => new DatabaseOperations(
                    loggerProvider,
                    targetName,
                    startupTargetName,
                    projectDir,
                    rootNamespace,
                    dnxServices));
            _migrationsOperations = new LazyRef <MigrationsOperations>(
                () => new MigrationsOperations(
                    loggerProvider,
                    targetName,
                    startupTargetName,
                    projectDir,
                    rootNamespace,
                    dnxServices));
        }
Exemplo n.º 41
0
        public ModificationCommand(
            [NotNull] string name,
            [CanBeNull] string schemaName,
            [NotNull] ParameterNameGenerator parameterNameGenerator,
            [NotNull] Func <IProperty, IRelationalPropertyAnnotations> getPropertyExtensions,
            [NotNull] IRelationalValueBufferFactoryFactory valueBufferFactoryFactory)
        {
            Check.NotEmpty(name, nameof(name));
            Check.NotNull(parameterNameGenerator, nameof(parameterNameGenerator));
            Check.NotNull(getPropertyExtensions, nameof(getPropertyExtensions));
            Check.NotNull(valueBufferFactoryFactory, nameof(valueBufferFactoryFactory));

            TableName                  = name;
            SchemaName                 = schemaName;
            ParameterNameGenerator     = parameterNameGenerator;
            _getPropertyExtensions     = getPropertyExtensions;
            _valueBufferFactoryFactory = valueBufferFactoryFactory;

            _valueBufferFactory = new LazyRef <IRelationalValueBufferFactory>(CreateValueBufferFactory);
        }
        public ModificationCommand(
            [NotNull] string name,
            [CanBeNull] string schema,
            [NotNull] ParameterNameGenerator parameterNameGenerator,
            [NotNull] Func<IProperty, IRelationalPropertyAnnotations> getPropertyExtensions,
            [NotNull] IRelationalValueBufferFactoryFactory valueBufferFactoryFactory)
        {
            Check.NotEmpty(name, nameof(name));
            Check.NotNull(parameterNameGenerator, nameof(parameterNameGenerator));
            Check.NotNull(getPropertyExtensions, nameof(getPropertyExtensions));
            Check.NotNull(valueBufferFactoryFactory, nameof(valueBufferFactoryFactory));

            TableName = name;
            Schema = schema;
            ParameterNameGenerator = parameterNameGenerator;
            _getPropertyExtensions = getPropertyExtensions;
            _valueBufferFactoryFactory = valueBufferFactoryFactory;

            _valueBufferFactory = new LazyRef<IRelationalValueBufferFactory>(CreateValueBufferFactory);
        }
Exemplo n.º 43
0
        protected QueryContextFactory(
            [NotNull] IStateManager stateManager,
            [NotNull] IEntityKeyFactorySource entityKeyFactorySource,
            [NotNull] IClrCollectionAccessorSource collectionAccessorSource,
            [NotNull] IClrAccessorSource <IClrPropertySetter> propertySetterSource,
            [NotNull] ILoggerFactory loggerFactory)
        {
            Check.NotNull(stateManager, nameof(stateManager));
            Check.NotNull(entityKeyFactorySource, nameof(entityKeyFactorySource));
            Check.NotNull(collectionAccessorSource, nameof(collectionAccessorSource));
            Check.NotNull(propertySetterSource, nameof(propertySetterSource));
            Check.NotNull(loggerFactory, nameof(loggerFactory));

            _stateManager             = stateManager;
            _entityKeyFactorySource   = entityKeyFactorySource;
            _collectionAccessorSource = collectionAccessorSource;
            _propertySetterSource     = propertySetterSource;

            _logger = new LazyRef <ILogger>(loggerFactory.CreateLogger <QueryContextFactory>);
        }
Exemplo n.º 44
0
            internal Instruction(int index, IBinaryReader binaryReader, Context.IOperandReaderContext context)
            {
                this.Index  = index;
                this.Offset = binaryReader.Offset;
                this.OpCode = OpCodeReader.ReadOpCode(binaryReader);
                // Operand
                bool argumentAware = OperandReader.IsArgumentAware(OpCode);

                if (argumentAware)
                {
                    this.Operand = OperandReader.ReadArg(binaryReader, context, OpCode.OperandType);
                    argIndex     = OperandReader.GetArgIndex(OpCode, binaryReader);
                    if (argIndex.Value > 0)
                    {
                        this.rawOperand = context[(short)(argIndex.Value - 1), true];
                    }
                    else
                    {
                        this.rawOperand = context.This;
                    }
                }
                bool localAware = OperandReader.IsLocalAware(OpCode);

                if (localAware)
                {
                    this.Operand = OperandReader.Read(binaryReader, context, OpCode.OperandType);
                    locIndex     = OperandReader.GetLocalIndex(OpCode, binaryReader);
                    if (Operand == null)
                    {
                        this.rawOperand = context[locIndex.Value, false];
                    }
                }
                if (!localAware && !argumentAware)
                {
                    this.Operand = OperandReader.Read(binaryReader, context, OpCode.OperandType);
                }
                //
                int size = binaryReader.Offset - Offset;

                this.bytes = new LazyRef <byte[]>(() => binaryReader.Read(Offset, size));
            }
Exemplo n.º 45
0
        public MigrationAssembly(
            [NotNull] DbContext context,
            [NotNull] IDbContextOptions options,
            [NotNull] IMigrationModelFactory modelFactory)
        {
            Check.NotNull(context, nameof(context));
            Check.NotNull(options, nameof(options));
            Check.NotNull(modelFactory, nameof(modelFactory));

            var contextType = context.GetType();

            var assemblyName = RelationalOptionsExtension.Extract(options)?.MigrationsAssembly;
            var assembly     = assemblyName == null
                ? contextType.GetTypeInfo().Assembly
                : Assembly.Load(new AssemblyName(assemblyName));

            _migrations = new LazyRef <IReadOnlyList <Migration> >(
                () => GetMigrationTypes(assembly)
                .Where(t => TryGetContextType(t) == contextType)
                .Select(t => (Migration)Activator.CreateInstance(t.AsType()))
                .OrderBy(m => m.Id)
                .ToList());
            _modelSnapshot = new LazyRef <ModelSnapshot>(
                () => (
                    from t in GetTypes(assembly)
                    where t.IsSubclassOf(typeof(ModelSnapshot)) &&
                    TryGetContextType(t) == contextType
                    select(ModelSnapshot) Activator.CreateInstance(t.AsType()))
                .FirstOrDefault());
            _lastModel = new LazyRef <IModel>(
                () =>
            {
                if (_modelSnapshot.Value == null)
                {
                    return(null);
                }

                return(modelFactory.Create(_modelSnapshot.Value.BuildModel));
            });
        }
Exemplo n.º 46
0
            public Executor(string targetProject, string environment, bool verbose)
            {
                var appEnv         = PlatformServices.Default.Application;
                var libraryManager = PlatformServices.Default.LibraryManager;

                var loggerProvider = new LoggerProvider(name => new ConsoleCommandLogger(name, verbose, _ansiConsole));

                _logger = new LazyRef <ILogger>(() => loggerProvider.CreateCommandsLogger());

                var targetName = !string.IsNullOrEmpty(targetProject)
                    ? targetProject
                    : appEnv.ApplicationName;
                var startupTargetName = appEnv.ApplicationName;
                var targetLibrary     = libraryManager.GetLibrary(targetName);
                var projectDir        = Path.GetDirectoryName(targetLibrary.Path);
                var rootNamespace     = targetLibrary.Name;

                _contextOperations = new LazyRef <DbContextOperations>(
                    () => new DbContextOperations(
                        loggerProvider,
                        targetName,
                        startupTargetName,
                        environment));
                _databaseOperations = new LazyRef <DatabaseOperations>(
                    () => new DatabaseOperations(
                        loggerProvider,
                        targetName,
                        startupTargetName,
                        environment,
                        projectDir,
                        rootNamespace));
                _migrationsOperations = new LazyRef <MigrationsOperations>(
                    () => new MigrationsOperations(
                        loggerProvider,
                        targetName,
                        startupTargetName,
                        environment,
                        projectDir,
                        rootNamespace));
            }
Exemplo n.º 47
0
        public Migrator(
            [NotNull] IMigrationAssembly migrationAssembly,
            [NotNull] IHistoryRepository historyRepository,
            [NotNull] IDataStoreCreator dataStoreCreator,
            [NotNull] IMigrationSqlGenerator migrationSqlGenerator,
            [NotNull] ISqlStatementExecutor executor,
            [NotNull] IRelationalConnection connection,
            [NotNull] IModelDiffer modelDiffer,
            [NotNull] IModel model,
            [NotNull] IMigrationIdGenerator idGenerator,
            [NotNull] ISqlGenerator sqlGenerator,
            [NotNull] ILoggerFactory loggerFactory,
            [NotNull] IMigrationModelFactory modelFactory)
        {
            Check.NotNull(migrationAssembly, nameof(migrationAssembly));
            Check.NotNull(historyRepository, nameof(historyRepository));
            Check.NotNull(dataStoreCreator, nameof(dataStoreCreator));
            Check.NotNull(migrationSqlGenerator, nameof(migrationSqlGenerator));
            Check.NotNull(executor, nameof(executor));
            Check.NotNull(connection, nameof(connection));
            Check.NotNull(modelDiffer, nameof(modelDiffer));
            Check.NotNull(model, nameof(model));
            Check.NotNull(idGenerator, nameof(idGenerator));
            Check.NotNull(sqlGenerator, nameof(sqlGenerator));
            Check.NotNull(loggerFactory, nameof(loggerFactory));
            Check.NotNull(modelFactory, nameof(modelFactory));

            _migrationAssembly     = migrationAssembly;
            _historyRepository     = historyRepository;
            _dataStoreCreator      = (IRelationalDataStoreCreator)dataStoreCreator;
            _migrationSqlGenerator = migrationSqlGenerator;
            _executor     = executor;
            _connection   = connection;
            _modelDiffer  = modelDiffer;
            _model        = model;
            _idGenerator  = idGenerator;
            _sqlGenerator = sqlGenerator;
            _logger       = new LazyRef <ILogger>(loggerFactory.CreateLogger <Migrator>);
            _modelFactory = modelFactory;
        }
Exemplo n.º 48
0
        public DatabaseTool(
            [CanBeNull] IServiceProvider serviceProvider,
            [NotNull] ILoggerProvider loggerProvider)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));

            _serviceProvider = new ServiceProvider(serviceProvider);
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);
            _logger = new LazyRef <ILogger>(() => loggerFactory.CreateLogger <DatabaseTool>());
            _serviceProvider.AddService(typeof(ILogger), _logger.Value);
            _serviceProvider.AddService(typeof(IFileService), new FileSystemFileService());
            _serviceProvider.AddService(typeof(CSharpCodeGeneratorHelper), new CSharpCodeGeneratorHelper());
            _serviceProvider.AddService(typeof(ModelUtilities), new ModelUtilities());
            var metadataReferencesProvider = new MetadataReferencesProvider(_serviceProvider);

            _serviceProvider.AddService(typeof(MetadataReferencesProvider), metadataReferencesProvider);
            var compilationService = new RoslynCompilationService();

            _serviceProvider.AddService(typeof(ITemplating), new RazorTemplating(compilationService, metadataReferencesProvider));
        }
Exemplo n.º 49
0
        public ColumnModification(
            [NotNull] InternalEntityEntry entry,
            [NotNull] IProperty property,
            [NotNull] IRelationalPropertyExtensions propertyExtensions,
            [NotNull] ParameterNameGenerator parameterNameGenerator,
            [CanBeNull] IBoxedValueReader boxedValueReader,
            bool isRead,
            bool isWrite,
            bool isKey,
            bool isCondition)
        {
            Check.NotNull(entry, nameof(entry));
            Check.NotNull(property, nameof(property));
            Check.NotNull(propertyExtensions, nameof(propertyExtensions));
            Check.NotNull(parameterNameGenerator, nameof(parameterNameGenerator));

            Debug.Assert(!isRead || boxedValueReader != null);

            Entry      = entry;
            Property   = property;
            ColumnName = propertyExtensions.Column;

            _parameterName = isWrite
                ? new LazyRef <string>(parameterNameGenerator.GenerateNext)
                : new LazyRef <string>((string)null);
            _originalParameterName = isCondition
                ? new LazyRef <string>(parameterNameGenerator.GenerateNext)
                : new LazyRef <string>((string)null);
            _outputParameterName = isRead
                ? new LazyRef <string>(parameterNameGenerator.GenerateNext)
                : new LazyRef <string>((string)null);

            BoxedValueReader = boxedValueReader;

            IsRead      = isRead;
            IsWrite     = isWrite;
            IsKey       = isKey;
            IsCondition = isCondition;
        }
Exemplo n.º 50
0
        public virtual DbContextServices Initialize(
            [NotNull] IServiceProvider scopedProvider,
            [NotNull] DbContextOptions contextOptions,
            [NotNull] DbContext context,
            ServiceProviderSource serviceProviderSource)
        {
            Check.NotNull(scopedProvider, "scopedProvider");
            Check.NotNull(contextOptions, "contextOptions");
            Check.NotNull(context, "context");
            Check.IsDefined(serviceProviderSource, "serviceProviderSource");

            _scopedProvider = scopedProvider;
            _contextOptions = contextOptions;
            _context        = context;

            _dataStoreServices = new LazyRef <DataStoreServices>(() =>
                                                                 _scopedProvider.GetRequiredServiceChecked <DataStoreSelector>().SelectDataStore(serviceProviderSource));

            _modelFromSource = new LazyRef <IModel>(CreateModel);

            return(this);
        }
Exemplo n.º 51
0
        public DbContextOperations([NotNull] ILoggerProvider loggerProvider,
                                   [NotNull] Assembly assembly,
                                   [NotNull] Assembly startupAssembly,
                                   [CanBeNull] string environment,
                                   [NotNull] string contentRootPath)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotNull(assembly, nameof(assembly));
            Check.NotNull(startupAssembly, nameof(startupAssembly));
            Check.NotEmpty(contentRootPath, nameof(contentRootPath));

            _loggerProvider  = loggerProvider;
            _assembly        = assembly;
            _startupAssembly = startupAssembly;
            _environment     = environment;
            _contentRootPath = contentRootPath;
            _logger          = new LazyRef <ILogger>(() => _loggerProvider.CreateCommandsLogger());

            var startup = new StartupInvoker(_logger, startupAssembly, environment, contentRootPath);

            _runtimeServices = startup.ConfigureServices();
        }
Exemplo n.º 52
0
        protected RelationalConnection([NotNull] IDbContextOptions options, [NotNull] ILogger logger)
        {
            Check.NotNull(options, nameof(options));
            Check.NotNull(logger, nameof(logger));

            _logger = logger;

            var relationalOptions = RelationalOptionsExtension.Extract(options);

            _commandTimeout = relationalOptions.CommandTimeout;

            if (relationalOptions.Connection != null)
            {
                if (!string.IsNullOrWhiteSpace(relationalOptions.ConnectionString))
                {
                    throw new InvalidOperationException(RelationalStrings.ConnectionAndConnectionString);
                }

                _connection      = new LazyRef <DbConnection>(() => relationalOptions.Connection);
                _connectionOwned = false;
                _openedCount     = relationalOptions.Connection.State == ConnectionState.Open ? 1 : 0;
            }
            else if (!string.IsNullOrWhiteSpace(relationalOptions.ConnectionString))
            {
                _connectionString = relationalOptions.ConnectionString;
                _connection       = new LazyRef <DbConnection>(CreateDbConnection);
                _connectionOwned  = true;
            }
            else
            {
                throw new InvalidOperationException(RelationalStrings.NoConnectionOrConnectionString);
            }

#if NET45
            _throwOnAmbientTransaction = relationalOptions.ThrowOnAmbientTransaction ?? true;
#endif
        }
Exemplo n.º 53
0
        public OperationExecutor([NotNull] object logHandler, [NotNull] IDictionary args)
        {
            Check.NotNull(logHandler, nameof(logHandler));
            Check.NotNull(args, nameof(args));

            var unwrappedLogHandler = ForwardingProxy.Unwrap <IOperationLogHandler>(logHandler);
            var loggerProvider      = new LoggerProvider(name => new CommandLoggerAdapter(name, unwrappedLogHandler));

            var targetName        = (string)args["targetName"];
            var startupTargetName = (string)args["startupTargetName"];
            var environment       = (string)args["environment"];
            var projectDir        = (string)args["projectDir"];
            var rootNamespace     = (string)args["rootNamespace"];

            _contextOperations = new LazyRef <DbContextOperations>(
                () => new DbContextOperations(
                    loggerProvider,
                    targetName,
                    startupTargetName,
                    environment));
            _databaseOperations = new LazyRef <DatabaseOperations>(
                () => new DatabaseOperations(
                    loggerProvider,
                    targetName,
                    startupTargetName,
                    environment,
                    projectDir,
                    rootNamespace));
            _migrationsOperations = new LazyRef <MigrationsOperations>(
                () => new MigrationsOperations(
                    loggerProvider,
                    targetName,
                    startupTargetName,
                    environment,
                    projectDir,
                    rootNamespace));
        }
        /// <summary>
        ///     Initializes a new instance of this class.
        /// </summary>
        /// <param name="dependencies"> Parameter object containing dependencies for this service. </param>
        protected HistoryRepository([NotNull] HistoryRepositoryDependencies dependencies)
        {
            Check.NotNull(dependencies, nameof(dependencies));

            Dependencies = dependencies;

            var relationalOptions = RelationalOptionsExtension.Extract(dependencies.Options);

            TableName   = relationalOptions?.MigrationsHistoryTableName ?? DefaultTableName;
            TableSchema = relationalOptions?.MigrationsHistoryTableSchema;
            _model      = new LazyRef <IModel>(
                () =>
            {
                var conventionSet = Dependencies.CoreConventionSetBuilder.CreateConventionSet();
                foreach (var conventionSetBuilder in Dependencies.ConventionSetBuilders)
                {
                    conventionSet = conventionSetBuilder.AddConventions(conventionSet);
                }

                var modelBuilder = new ModelBuilder(conventionSet);

                modelBuilder.Entity <HistoryRow>(
                    x =>
                {
                    ConfigureTable(x);
                    x.ToTable(TableName, TableSchema);
                });

                return(modelBuilder.Model);
            });
            var entityType = new LazyRef <IEntityType>(() => _model.Value.FindEntityType(typeof(HistoryRow)));

            _migrationIdColumnName = new LazyRef <string>(
                () => entityType.Value.FindProperty(nameof(HistoryRow.MigrationId)).Relational().ColumnName);
            _productVersionColumnName = new LazyRef <string>(
                () => entityType.Value.FindProperty(nameof(HistoryRow.ProductVersion)).Relational().ColumnName);
        }
Exemplo n.º 55
0
        public MigrationsOperations(
            [NotNull] ILoggerProvider loggerProvider,
            [NotNull] Assembly assembly,
            [NotNull] AssemblyLoader startupAssemblyLoader,
            [NotNull] Assembly startupAssembly,
            [CanBeNull] string environment,
            [NotNull] string projectDir,
            [NotNull] string startupProjectDir,
            [NotNull] string rootNamespace)
        {
            Check.NotNull(startupAssemblyLoader, nameof(startupAssemblyLoader));
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotNull(assembly, nameof(assembly));
            Check.NotNull(startupAssembly, nameof(startupAssembly));
            Check.NotNull(projectDir, nameof(projectDir));
            Check.NotEmpty(startupProjectDir, nameof(startupProjectDir));
            Check.NotNull(rootNamespace, nameof(rootNamespace));

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);

            _logger            = new LazyRef <ILogger>(() => loggerFactory.CreateCommandsLogger());
            _assembly          = assembly;
            _projectDir        = projectDir;
            _rootNamespace     = rootNamespace;
            _contextOperations = new DbContextOperations(
                loggerProvider,
                assembly,
                startupAssembly,
                environment,
                startupProjectDir);

            var startup = new StartupInvoker(startupAssembly, environment, startupProjectDir);

            _servicesBuilder = new DesignTimeServicesBuilder(startupAssemblyLoader, startup);
        }
Exemplo n.º 56
0
        protected RelationalConnection([NotNull] IEntityOptions options, [NotNull] ILoggerFactory loggerFactory)
        {
            Check.NotNull(options, nameof(options));
            Check.NotNull(loggerFactory, nameof(loggerFactory));

            _logger = new LazyRef <ILogger>(loggerFactory.CreateLogger <RelationalConnection>);

            var storeConfig = RelationalOptionsExtension.Extract(options);

            _commandTimeout = storeConfig.CommandTimeout;

            if (storeConfig.Connection != null)
            {
                if (!string.IsNullOrWhiteSpace(storeConfig.ConnectionString))
                {
                    throw new InvalidOperationException(Strings.ConnectionAndConnectionString);
                }

                _connection      = new LazyRef <DbConnection>(() => storeConfig.Connection);
                _connectionOwned = false;
                _openedCount     = storeConfig.Connection.State == ConnectionState.Open ? 1 : 0;
            }
            else if (!string.IsNullOrWhiteSpace(storeConfig.ConnectionString))
            {
                _connectionString = storeConfig.ConnectionString;
                _connection       = new LazyRef <DbConnection>(CreateDbConnection);
                _connectionOwned  = true;
            }
            else
            {
                throw new InvalidOperationException(Strings.NoConnectionOrConnectionString);
            }

#if NET45
            _throwOnAmbientTransaction = storeConfig.ThrowOnAmbientTransaction ?? true;
#endif
        }
        public DbContextOperations(
            [NotNull] ILoggerProvider loggerProvider,
            [NotNull] Assembly assembly,
            [NotNull] Assembly startupAssembly,
            [NotNull] string projectDir,
            [CanBeNull] string environment)
        {
            Check.NotNull(loggerProvider, nameof(loggerProvider));
            Check.NotNull(assembly, nameof(assembly));
            Check.NotNull(startupAssembly, nameof(startupAssembly));
            Check.NotEmpty(projectDir, nameof(projectDir));

            _loggerProvider  = loggerProvider;
            _assembly        = assembly;
            _startupAssembly = startupAssembly;
            _projectDir      = projectDir;
            _logger          = new LazyRef <ILogger>(() => _loggerProvider.CreateCommandsLogger());

            var startup = new StartupInvoker(startupAssembly, environment);

            _runtimeServices = startup.ConfigureServices();

            _servicesBuilder = new DesignTimeServicesBuilder(startup);
        }
Exemplo n.º 58
0
        public static IRelationalCommand GetDbCommand <T>(this IQueryable <T> query)
        {
            bool isEFCore2x = false;

            // REFLECTION: Query._context
            var contextField = query.GetType().GetField("_context", BindingFlags.NonPublic | BindingFlags.Instance);
            var context      = (DbContext)contextField.GetValue(query);

            // REFLECTION: Query._context.StateManager
            var stateManagerProperty = typeof(DbContext).GetProperty("StateManager", BindingFlags.NonPublic | BindingFlags.Instance);
            var stateManager         = (StateManager)stateManagerProperty.GetValue(context);

            // REFLECTION: Query._context.StateManager._concurrencyDetector
            var concurrencyDetectorField = typeof(StateManager).GetField("_concurrencyDetector", BindingFlags.NonPublic | BindingFlags.Instance);
            var concurrencyDetector      = (IConcurrencyDetector)concurrencyDetectorField.GetValue(stateManager);

            // REFLECTION: Query.Provider._queryCompiler
            var queryCompilerField = typeof(EntityQueryProvider).GetField("_queryCompiler", BindingFlags.NonPublic | BindingFlags.Instance);
            var queryCompiler      = queryCompilerField.GetValue(query.Provider);

            // REFLECTION: Query.Provider.NodeTypeProvider (Use property for nullable logic)
            var nodeTypeProviderField = queryCompiler.GetType().GetProperty("NodeTypeProvider", BindingFlags.NonPublic | BindingFlags.Instance);
            var nodeTypeProvider      = nodeTypeProviderField.GetValue(queryCompiler);

            // REFLECTION: Query.Provider._queryCompiler.CreateQueryParser();
            var createQueryParserMethod = queryCompiler.GetType().GetMethod("CreateQueryParser", BindingFlags.NonPublic | BindingFlags.Static);
            var createQueryParser       = (QueryParser)createQueryParserMethod.Invoke(null, new[] { nodeTypeProvider });

            // REFLECTION: Query.Provider._queryCompiler._database
            var databaseField = queryCompiler.GetType().GetField("_database", BindingFlags.NonPublic | BindingFlags.Instance);
            var database      = (IDatabase)databaseField.GetValue(queryCompiler);

            // REFLECTION: Query.Provider._queryCompiler._evaluatableExpressionFilter
            var evaluatableExpressionFilterField = queryCompiler.GetType().GetField("_evaluatableExpressionFilter", BindingFlags.NonPublic | BindingFlags.Static);
            var evaluatableExpressionFilter      = (IEvaluatableExpressionFilter)evaluatableExpressionFilterField.GetValue(null);

            // REFLECTION: Query.Provider._queryCompiler._queryContextFactory
            var queryContextFactoryField = queryCompiler.GetType().GetField("_queryContextFactory", BindingFlags.NonPublic | BindingFlags.Instance);
            var queryContextFactory      = (IQueryContextFactory)queryContextFactoryField.GetValue(queryCompiler);

            // REFLECTION: Query.Provider._queryCompiler._queryContextFactory.CreateQueryBuffer
            var createQueryBufferDelegateMethod = (typeof(QueryContextFactory)).GetMethod("CreateQueryBuffer", BindingFlags.NonPublic | BindingFlags.Instance);
            var createQueryBufferDelegate       = (Func <IQueryBuffer>)createQueryBufferDelegateMethod.CreateDelegate(typeof(Func <IQueryBuffer>), queryContextFactory);

            // REFLECTION: Query.Provider._queryCompiler._queryContextFactory._connection
            var connectionField = queryContextFactory.GetType().GetField("_connection", BindingFlags.NonPublic | BindingFlags.Instance);
            var connection      = (IRelationalConnection)connectionField.GetValue(queryContextFactory);

            // REFLECTION: Query.Provider._queryCompiler._database._queryCompilationContextFactory
            object logger;

            var dependenciesProperty = typeof(Database).GetProperty("Dependencies", BindingFlags.NonPublic | BindingFlags.Instance);
            IQueryCompilationContextFactory queryCompilationContextFactory;

            if (dependenciesProperty != null)
            {
                // EF Core 2.x
                isEFCore2x = true;

                var dependencies = dependenciesProperty.GetValue(database);

                var queryCompilationContextFactoryField = typeof(DbContext).GetTypeFromAssembly_Core("Microsoft.EntityFrameworkCore.Storage.DatabaseDependencies")
                                                          .GetProperty("QueryCompilationContextFactory", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                queryCompilationContextFactory = (IQueryCompilationContextFactory)queryCompilationContextFactoryField.GetValue(dependencies);

                var dependenciesProperty2 = typeof(QueryCompilationContextFactory).GetProperty("Dependencies", BindingFlags.NonPublic | BindingFlags.Instance);
                var dependencies2         = dependenciesProperty2.GetValue(queryCompilationContextFactory);

                // REFLECTION: Query.Provider._queryCompiler._database._queryCompilationContextFactory.Logger
                var loggerField = typeof(DbContext).GetTypeFromAssembly_Core("Microsoft.EntityFrameworkCore.Query.Internal.QueryCompilationContextDependencies")
                                  .GetProperty("Logger", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                // (IInterceptingLogger<LoggerCategory.Query>)
                logger = loggerField.GetValue(dependencies2);
            }
            else
            {
                // EF Core 1.x
                var queryCompilationContextFactoryField = typeof(Database).GetField("_queryCompilationContextFactory", BindingFlags.NonPublic | BindingFlags.Instance);
                queryCompilationContextFactory = (IQueryCompilationContextFactory)queryCompilationContextFactoryField.GetValue(database);

                // REFLECTION: Query.Provider._queryCompiler._database._queryCompilationContextFactory.Logger
                var loggerField = queryCompilationContextFactory.GetType().GetProperty("Logger", BindingFlags.NonPublic | BindingFlags.Instance);
                //
                logger = loggerField.GetValue(queryCompilationContextFactory);
            }


            // CREATE query context
            RelationalQueryContext queryContext;
            {
                var relationalQueryContextType        = typeof(RelationalQueryContext);
                var relationalQueryContextConstructor = relationalQueryContextType.GetConstructors()[0];

                // EF Core 1.1 preview
                if (relationalQueryContextConstructor.GetParameters().Length == 5)
                {
                    // REFLECTION: Query.Provider._queryCompiler._queryContextFactory.ExecutionStrategyFactory
                    var executionStrategyFactoryField = queryContextFactory.GetType().GetProperty("ExecutionStrategyFactory", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                    var executionStrategyFactory      = executionStrategyFactoryField.GetValue(queryContextFactory);

                    var lazyRefStateManager = new LazyRef <IStateManager>(() => stateManager);

                    queryContext = (RelationalQueryContext)relationalQueryContextConstructor.Invoke(new object[] { createQueryBufferDelegate, connection, lazyRefStateManager, concurrencyDetector, executionStrategyFactory });
                }
                else
                {
                    queryContext = (RelationalQueryContext)relationalQueryContextConstructor.Invoke(new object[] { createQueryBufferDelegate, connection, stateManager, concurrencyDetector });
                }
            }


            Expression newQuery;

            if (isEFCore2x)
            {
                var parameterExtractingExpressionVisitorConstructor = typeof(ParameterExtractingExpressionVisitor).GetConstructors().First(x => x.GetParameters().Length == 5);

                var parameterExtractingExpressionVisitor = (ParameterExtractingExpressionVisitor)parameterExtractingExpressionVisitorConstructor.Invoke(new object[] { evaluatableExpressionFilter, queryContext, logger, false, false });

                // CREATE new query from query visitor
                newQuery = parameterExtractingExpressionVisitor.ExtractParameters(query.Expression);
            }
            else
            {
                // CREATE new query from query visitor
                var extractParametersMethods = typeof(ParameterExtractingExpressionVisitor).GetMethod("ExtractParameters", BindingFlags.Public | BindingFlags.Static);
                newQuery = (Expression)extractParametersMethods.Invoke(null, new object[] { query.Expression, queryContext, evaluatableExpressionFilter, logger });
            }

            // PARSE new query
            var queryModel = createQueryParser.GetParsedQuery(newQuery);

            // CREATE query model visitor
            var queryModelVisitor = (RelationalQueryModelVisitor)queryCompilationContextFactory.Create(false).CreateQueryModelVisitor();

            // REFLECTION: Query.Provider._queryCompiler._database._queryCompilationContextFactory.Create(false).CreateQueryModelVisitor().CreateQueryExecutor()
            var createQueryExecutorMethod        = queryModelVisitor.GetType().GetMethod("CreateQueryExecutor");
            var createQueryExecutorMethodGeneric = createQueryExecutorMethod.MakeGenericMethod(query.ElementType);

            createQueryExecutorMethodGeneric.Invoke(queryModelVisitor, new[] { queryModel });

            // RETURN the IRealationCommand
            var sqlQuery          = queryModelVisitor.Queries.First();
            var relationalCommand = sqlQuery.CreateDefaultQuerySqlGenerator().GenerateSql(queryContext.ParameterValues);

            return(relationalCommand);
        }
        /// <summary>
        ///     <para>Initializes a new instance of the <see cref="OperationExecutor" /> class.</para>
        ///     <para>The arguments supported by <paramref name="args" /> are:</para>
        ///     <para><c>targetName</c>--The assembly name of the target project.</para>
        ///     <para><c>startupTargetName</c>--The assembly name of the startup project.</para>
        ///     <para><c>projectDir</c>--The target project's root directory.</para>
        ///     <para><c>rootNamespace</c>--The target project's root namespace.</para>
        /// </summary>
        /// <param name="reportHandler"> The <see cref="IOperationReportHandler" />. </param>
        /// <param name="args"> The executor arguments. </param>
        public OperationExecutor([NotNull] object reportHandler, [NotNull] IDictionary args)
        {
            Check.NotNull(reportHandler, nameof(reportHandler));
            Check.NotNull(args, nameof(args));

            var unwrappedReportHandler = ForwardingProxy.Unwrap <IOperationReportHandler>(reportHandler);
            var reporter = new OperationReporter(unwrappedReportHandler);

            var targetName        = (string)args["targetName"];
            var startupTargetName = (string)args["startupTargetName"];

            _projectDir = (string)args["projectDir"];
            var rootNamespace = (string)args["rootNamespace"];
            var language      = (string)args["language"];
            var toolsVersion  = (string)args["toolsVersion"];

            // TODO: Flow in from tools (issue #8332)
            var designArgs = Array.Empty <string>();

            var runtimeVersion = ProductInfo.GetVersion();

            if (toolsVersion != null &&
                new SemanticVersionComparer().Compare(RemovePatch(toolsVersion), RemovePatch(runtimeVersion)) < 0)
            {
                reporter.WriteWarning(DesignStrings.VersionMismatch(toolsVersion, runtimeVersion));
            }

            // NOTE: LazyRef is used so any exceptions get passed to the resultHandler
            var startupAssembly = new LazyRef <Assembly>(
                () => Assembly.Load(new AssemblyName(startupTargetName)));
            var assembly = new LazyRef <Assembly>(
                () =>
            {
                try
                {
                    return(Assembly.Load(new AssemblyName(targetName)));
                }
                catch (Exception ex)
                {
                    throw new OperationException(
                        DesignStrings.UnreferencedAssembly(targetName, startupTargetName),
                        ex);
                }
            });

            _contextOperations = new LazyRef <DbContextOperations>(
                () => new DbContextOperations(
                    reporter,
                    assembly.Value,
                    startupAssembly.Value,
                    designArgs));
            _databaseOperations = new LazyRef <DatabaseOperations>(
                () => new DatabaseOperations(
                    reporter,
                    assembly.Value,
                    startupAssembly.Value,
                    _projectDir,
                    rootNamespace,
                    language,
                    designArgs));
            _migrationsOperations = new LazyRef <MigrationsOperations>(
                () => new MigrationsOperations(
                    reporter,
                    assembly.Value,
                    startupAssembly.Value,
                    _projectDir,
                    rootNamespace,
                    language,
                    designArgs));

            string RemovePatch(string versionString)
            {
                var prereleaseIndex = versionString.IndexOf("-", StringComparison.Ordinal);

                if (prereleaseIndex != -1)
                {
                    versionString = versionString.Substring(0, prereleaseIndex);
                }

                var version = new Version(versionString);

                return(new Version(version.Major, version.Minor).ToString());
            }
        }
        /// <summary>Creates executor and get command.</summary>
        /// <returns>The new executor and get command.</returns>
        public virtual IRelationalCommand CreateExecutorAndGetCommand(out RelationalQueryContext queryContext)
        {
            var context = Query.GetDbContext();

            // REFLECTION: Query._context.StateManager
            var stateManagerProperty = typeof(DbContext).GetProperty("StateManager", BindingFlags.NonPublic | BindingFlags.Instance);
            var stateManager         = (StateManager)stateManagerProperty.GetValue(context);

            // REFLECTION: Query._context.StateManager._concurrencyDetector
            var concurrencyDetectorField = typeof(StateManager).GetField("_concurrencyDetector", BindingFlags.NonPublic | BindingFlags.Instance);
            var concurrencyDetector      = (IConcurrencyDetector)concurrencyDetectorField.GetValue(stateManager);

            // REFLECTION: Query.Provider._queryCompiler
            var queryCompilerField = typeof(EntityQueryProvider).GetField("_queryCompiler", BindingFlags.NonPublic | BindingFlags.Instance);
            var queryCompiler      = queryCompilerField.GetValue(Query.Provider);

            // REFLECTION: Query.Provider.NodeTypeProvider (Use property for nullable logic)
            var nodeTypeProviderField = queryCompiler.GetType().GetProperty("NodeTypeProvider", BindingFlags.NonPublic | BindingFlags.Instance);
            var nodeTypeProvider      = nodeTypeProviderField.GetValue(queryCompiler);

            // REFLECTION: Query.Provider._queryCompiler.CreateQueryParser();
            var createQueryParserMethod = queryCompiler.GetType().GetMethod("CreateQueryParser", BindingFlags.NonPublic | BindingFlags.Static);
            var createQueryParser       = (QueryParser)createQueryParserMethod.Invoke(null, new[] { nodeTypeProvider });

            // REFLECTION: Query.Provider._queryCompiler._database
            var databaseField = queryCompiler.GetType().GetField("_database", BindingFlags.NonPublic | BindingFlags.Instance);
            var database      = (IDatabase)databaseField.GetValue(queryCompiler);

            // REFLECTION: Query.Provider._queryCompiler._evaluatableExpressionFilter
            var evaluatableExpressionFilterField = queryCompiler.GetType().GetField("_evaluatableExpressionFilter", BindingFlags.NonPublic | BindingFlags.Static);
            var evaluatableExpressionFilter      = (IEvaluatableExpressionFilter)evaluatableExpressionFilterField.GetValue(null);

            // REFLECTION: Query.Provider._queryCompiler._queryContextFactory
            var queryContextFactoryField = queryCompiler.GetType().GetField("_queryContextFactory", BindingFlags.NonPublic | BindingFlags.Instance);
            var queryContextFactory      = (IQueryContextFactory)queryContextFactoryField.GetValue(queryCompiler);

            // REFLECTION: Query.Provider._queryCompiler._queryContextFactory.CreateQueryBuffer
            var createQueryBufferDelegateMethod = (typeof(QueryContextFactory)).GetMethod("CreateQueryBuffer", BindingFlags.NonPublic | BindingFlags.Instance);
            var createQueryBufferDelegate       = (Func <IQueryBuffer>)createQueryBufferDelegateMethod.CreateDelegate(typeof(Func <IQueryBuffer>), queryContextFactory);

            // REFLECTION: Query.Provider._queryCompiler._queryContextFactory._connection
            var connectionField = queryContextFactory.GetType().GetField("_connection", BindingFlags.NonPublic | BindingFlags.Instance);
            var connection      = (IRelationalConnection)connectionField.GetValue(queryContextFactory);

            // REFLECTION: Query.Provider._queryCompiler._database._queryCompilationContextFactory
            var queryCompilationContextFactoryField = typeof(Database).GetField("_queryCompilationContextFactory", BindingFlags.NonPublic | BindingFlags.Instance);
            var queryCompilationContextFactory      = (IQueryCompilationContextFactory)queryCompilationContextFactoryField.GetValue(database);

            // CREATE connection
            QueryConnection = new CreateEntityRelationConnection(connection);

            // CREATE query context
            {
                var relationalQueryContextType        = typeof(RelationalQueryContext);
                var relationalQueryContextConstructor = relationalQueryContextType.GetConstructors()[0];

                // EF Core 1.1 preview
                if (relationalQueryContextConstructor.GetParameters().Length == 5)
                {
                    // REFLECTION: Query.Provider._queryCompiler._queryContextFactory.ExecutionStrategyFactory
                    var executionStrategyFactoryField = queryContextFactory.GetType().GetProperty("ExecutionStrategyFactory", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                    var executionStrategyFactory      = executionStrategyFactoryField.GetValue(queryContextFactory);

                    var lazyRefStateManager = new LazyRef <IStateManager>(() => stateManager);

                    queryContext = (RelationalQueryContext)relationalQueryContextConstructor.Invoke(new object[] { createQueryBufferDelegate, QueryConnection, lazyRefStateManager, concurrencyDetector, executionStrategyFactory });
                }
                else
                {
                    queryContext = (RelationalQueryContext)relationalQueryContextConstructor.Invoke(new object[] { createQueryBufferDelegate, QueryConnection, stateManager, concurrencyDetector });
                }
            }

            // REFLECTION: Query.Provider._queryCompiler._database._queryCompilationContextFactory.Logger
            var loggerField = queryCompilationContextFactory.GetType().GetProperty("Logger", BindingFlags.NonPublic | BindingFlags.Instance);
            var logger      = (ISensitiveDataLogger)loggerField.GetValue(queryCompilationContextFactory);

            // CREATE new query from query visitor
            var newQuery = ParameterExtractingExpressionVisitor.ExtractParameters(Query.Expression, queryContext, evaluatableExpressionFilter, logger);

            // PARSE new query
            var queryModel = createQueryParser.GetParsedQuery(newQuery);

            // CREATE query model visitor
            var queryModelVisitor = (RelationalQueryModelVisitor)queryCompilationContextFactory.Create(false).CreateQueryModelVisitor();

            // REFLECTION: Query.Provider._queryCompiler._database._queryCompilationContextFactory.Create(false).CreateQueryModelVisitor().CreateQueryExecutor()
            var createQueryExecutorMethod        = queryModelVisitor.GetType().GetMethod("CreateQueryExecutor");
            var createQueryExecutorMethodGeneric = createQueryExecutorMethod.MakeGenericMethod(Query.ElementType);
            var queryExecutor = createQueryExecutorMethodGeneric.Invoke(queryModelVisitor, new[] { queryModel });

            // SET value
            QueryExecutor = queryExecutor;
            QueryContext  = queryContext;

            // RETURN the IRealationCommand
            var sqlQuery          = queryModelVisitor.Queries.First();
            var relationalCommand = sqlQuery.CreateDefaultQuerySqlGenerator().GenerateSql(queryContext.ParameterValues);

            return(relationalCommand);
        }