public void Serialize(DbDatabaseMapping databaseMapping, DbProviderInfo providerInfo, XmlWriter xmlWriter)
        {
            DebugCheck.NotNull(xmlWriter);
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(providerInfo);
            Debug.Assert(databaseMapping.Model != null);
            Debug.Assert(databaseMapping.Database != null);

            _xmlWriter = xmlWriter;
            _databaseMapping = databaseMapping;
            _version = databaseMapping.Model.SchemaVersion;
            _providerInfo = providerInfo;
            _namespace = Equals(_version, XmlConstants.EdmVersionForV3)
                             ? EdmXmlNamespaceV3
                             : (Equals(_version, XmlConstants.EdmVersionForV2) ? EdmXmlNamespaceV2 : EdmXmlNamespaceV1);

            _xmlWriter.WriteStartDocument();

            using (Element("Edmx", "Version", string.Format(CultureInfo.InvariantCulture, "{0:F1}", _version)))
            {
                WriteEdmxRuntime();
                WriteEdmxDesigner();
            }

            _xmlWriter.WriteEndDocument();
            _xmlWriter.Flush();
        }
        public void Invariant_name_and_manifest_token_properties_return_set_values()
        {
            var key = new DbProviderInfo("Bill", "Ben");

            Assert.Equal("Bill", key.ProviderInvariantName);
            Assert.Equal("Ben", key.ProviderManifestToken);
        }
        public static StorageMappingItemCollection GetStorageMappingItemCollection(
            this XDocument model, out DbProviderInfo providerInfo)
        {
            DebugCheck.NotNull(model);

            var edmItemCollection
                = new EdmItemCollection(
                    new[]
                        {
                            model.Descendants(EdmXNames.Csdl.SchemaNames).Single().CreateReader()
                        });

            var ssdlSchemaElement = model.Descendants(EdmXNames.Ssdl.SchemaNames).Single();

            providerInfo = new DbProviderInfo(
                ssdlSchemaElement.ProviderAttribute(),
                ssdlSchemaElement.ProviderManifestTokenAttribute());

            var storeItemCollection
                = new StoreItemCollection(
                    new[]
                        {
                            ssdlSchemaElement.CreateReader()
                        });

            return new StorageMappingItemCollection(
                edmItemCollection,
                storeItemCollection,
                new[] { new XElement(model.Descendants(EdmXNames.Msl.MappingNames).Single()).CreateReader() });
        }
        public void Serialize(DbDatabaseMapping databaseMapping, DbProviderInfo providerInfo, XmlWriter xmlWriter)
        {
            //Contract.Requires(xmlWriter != null);
            //Contract.Requires(databaseMapping != null);
            //Contract.Requires(providerInfo != null);
            Contract.Assert(databaseMapping.Model != null);
            Contract.Assert(databaseMapping.Database != null);

            _xmlWriter = xmlWriter;
            _databaseMapping = databaseMapping;
            _version = databaseMapping.Model.Version;
            _providerInfo = providerInfo;
            _namespace = _version == DataModelVersions.Version3 ? EdmXmlNamespaceV3 : EdmXmlNamespaceV2;

            _xmlWriter.WriteStartDocument();

            using (Element("Edmx", "Version", string.Format(CultureInfo.InvariantCulture, "{0:F1}", _version)))
            {
                WriteEdmxRuntime();
                WriteEdmxDesigner();
            }

            _xmlWriter.WriteEndDocument();
            _xmlWriter.Flush();
        }
        public static void SetProviderInfo(this EdmModel model, DbProviderInfo providerInfo)
        {
            //Contract.Requires(model != null);
            //Contract.Requires(providerInfo != null);

            model.Annotations.SetAnnotation(ProviderInfoAnnotation, providerInfo);
        }
 private CodeFirstCachedMetadataWorkspace(MetadataWorkspace metadataWorkspace, 
     IEnumerable<Assembly> assemblies, DbProviderInfo providerInfo, string defaultContainerName)
 {
     _metadataWorkspace = metadataWorkspace;
     _assemblies = assemblies;
     _providerInfo = providerInfo;
     _defaultContainerName = defaultContainerName;
 }
        public DatabaseMappingGenerator(DbProviderInfo providerInfo, DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(providerInfo);
            DebugCheck.NotNull(providerManifest);

            _providerInfo = providerInfo;
            _providerManifest = providerManifest;
        }
Example #8
0
        static DbCompiledModel CreateModel(Action<DbModelBuilder> configure)
        {
            var builder = new DbModelBuilder();
            //builder.Conventions.Remove<PluralizingEntitySetNameConvention>();
            configure(builder);

            var providerInfo = new DbProviderInfo(SqlCeProviderServices.ProviderInvariantName, "4.0");
            return builder.Build(providerInfo).Compile();
        }
Example #9
0
        internal DbModel(DbProviderInfo providerInfo, DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(providerInfo);
            DebugCheck.NotNull(providerManifest);

            _databaseMapping = new DbDatabaseMapping().Initialize(
                EdmModel.CreateConceptualModel(),
                EdmModel.CreateStoreModel(providerInfo, providerManifest));
        }
        public void Can_get_and_set_provider_annotation()
        {
            var database = new DbDatabaseMetadata().Initialize();
            var providerInfo = new DbProviderInfo("Foo", "Bar");

            database.SetProviderInfo(providerInfo);

            Assert.Same(providerInfo, database.GetProviderInfo());
        }
        public void Can_get_and_set_provider_annotation()
        {
            var database = new EdmModel(DataSpace.CSpace);
            var providerInfo = new DbProviderInfo("Foo", "Bar");

            database.ProviderInfo = providerInfo;

            Assert.Same(providerInfo, database.ProviderInfo);
        }
        internal DbDatabaseMapping BuildAndValidate(DbProviderInfo providerInfo)
        {
            var databaseMapping = base.Build(providerInfo).DatabaseMapping;

            //databaseMapping.ShellEdmx();

            databaseMapping.AssertValid();

            return databaseMapping;
        }
        public void GetProviderManifest_resolves_manifest()
        {
            var modelBuilder = new DbModelBuilder();
            var providerInfo = new DbProviderInfo("System.Data.SqlClient", "2012");
            var model = modelBuilder.Build(providerInfo);

            var providerServices = model.GetProviderManifest(DbConfiguration.DependencyResolver);

            Assert.NotNull(providerServices);
            Assert.Equal("SqlServer", providerServices.NamespaceName);
        }
Example #14
0
        static DbCompiledModel CreateModel()
        {
            var builder = new DbModelBuilder();
            builder.Conventions.Remove<PluralizingTableNameConvention>();

            builder.Entity<Language>().HasKey(m => m.Name);
            builder.Entity<EntityTranslationDbEntry>();

            var providerInfo = new DbProviderInfo(SqlCeProviderServices.ProviderInvariantName, "4.0");
            return builder.Build(providerInfo).Compile();
        }
        public void Equals_correctly_determines_equality()
        {
            var key = new DbProviderInfo("Bill", "Ben");

            Assert.True(key.Equals(key));
            Assert.True(key.Equals(new DbProviderInfo("Bill", "Ben")));
            Assert.False(key.Equals(new DbProviderInfo("Bill", "Men")));
            Assert.False(key.Equals(new DbProviderInfo("FlowerPot", "Ben")));
            Assert.False(key.Equals(null));
            Assert.False(key.Equals("Bill.And.Ben"));
        }
Example #16
0
        public void CanBuildCompiledDbModelProgrammatically()
        {
            var modelBuilder = new DbModelBuilder();

            modelBuilder.Entity<HR1.EntityObject_Product>().HasEntitySetName("Product");
            modelBuilder.Entity<HR1.EntityObject_Order>().HasEntitySetName("Order");
            modelBuilder.Entity<HR1.EntityObject_OrderLine>().HasEntitySetName("OrderLine");

            var providerInfo = new DbProviderInfo(providerInvariantName: "System.Data.SqlClient", providerManifestToken: "2012");
            var model = modelBuilder.Build(providerInfo);
            var compiledModel = model.Compile();
        }
        public static StoreItemCollection GetStoreItemCollection(this XDocument model, out DbProviderInfo providerInfo)
        {
            Contract.Requires(model != null);

            var schemaElement = model.Descendants(EdmXNames.Ssdl.SchemaNames).Single();

            providerInfo = new DbProviderInfo(
                schemaElement.ProviderAttribute(),
                schemaElement.ProviderManifestTokenAttribute());

            return new StoreItemCollection(new[] { schemaElement.CreateReader() });
        }
        // <summary>
        // Builds and stores the workspace based on the given code first configuration.
        // </summary>
        // <param name="databaseMapping"> The code first EDM model. </param>
        public CodeFirstCachedMetadataWorkspace(DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            _providerInfo = databaseMapping.ProviderInfo;
            _metadataWorkspace = databaseMapping.ToMetadataWorkspace();
            _assemblies = databaseMapping.Model.GetClrTypes().Select(t => t.Assembly()).Distinct().ToList();

            Debug.Assert(databaseMapping.Model.Containers.Count() == 1, "Expecting Code First to create only one container.");

            _defaultContainerName = databaseMapping.Model.Containers.First().Name;
        }
        public static DbProviderInfo GetProviderInfo(
            this DbConnection connection, out DbProviderManifest providerManifest)
        {
            //Contract.Requires(connection != null);

            var providerServices = DbProviderServices.GetProviderServices(connection);
            var providerManifestToken = providerServices.GetProviderManifestTokenChecked(connection);
            var providerInfo = new DbProviderInfo(connection.GetProviderInvariantName(), providerManifestToken);

            providerManifest = providerServices.GetProviderManifest(providerManifestToken);

            return providerInfo;
        }
        /// <summary>
        ///     Builds and stores the workspace based on the given code first configuration.
        /// </summary>
        /// <param name = "databaseMapping">The code first EDM model.</param>
        public CodeFirstCachedMetadataWorkspace(DbDatabaseMapping databaseMapping)
        {
            Contract.Requires(databaseMapping != null);

            _providerInfo = databaseMapping.Database.GetProviderInfo();

            _metadataWorkspace = databaseMapping.ToMetadataWorkspace();

            _assemblies = databaseMapping.Model.GetClrTypes().Select(t => t.Assembly).Distinct().ToList();

            Contract.Assert(
                databaseMapping.Model.Containers.Count() == 1, "Expecting Code First to create only one container.");
            _defaultContainerName = databaseMapping.Model.Containers.First().Name;
        }
Example #21
0
        internal static CommerceDbContext Create(CommerceInstanceSettings metadata, ICommerceDbProvider dbProvider)
        {
            var dbProviderInfo = new DbProviderInfo(metadata.DbProviderInvariantName, metadata.DbProviderManifestToken);

            var model = _modelCache.GetOrAdd(new ModelCacheKey(metadata.DbSchema, dbProviderInfo), key =>
            {
                return CreateModel(key.Schema, key.DbProviderInfo);
            });

            var dbProviderFactory = DbConfiguration.DependencyResolver.GetService(typeof(DbProviderFactory), dbProvider.InvariantName) as DbProviderFactory;
            var conn = dbProviderFactory.CreateConnection();
            conn.ConnectionString = dbProvider.GetConnectionString(metadata);

            return new CommerceDbContext(metadata, conn, model);
        }
        public static DbProviderInfo GetProviderInfo(
            this DbConnection connection, out DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(connection);

            var providerManifestToken = DbConfiguration
                .GetService<IManifestTokenService>()
                .GetProviderManifestToken(connection);

            var providerInfo = new DbProviderInfo(connection.GetProviderInvariantName(), providerManifestToken);

            providerManifest = DbProviderServices.GetProviderServices(connection).GetProviderManifest(providerManifestToken);

            return providerInfo;
        }
        internal DbDatabaseMapping BuildAndValidate(DbProviderInfo providerInfo, bool throwOnError, params Type[] unignoredTypes)
        {
            IgnoreAll(unignoredTypes);

            // Build and clone multiple times to check for idempotency issues.

            Build(providerInfo);

            var cloned = Clone();

            var databaseMapping = cloned.Build(providerInfo).DatabaseMapping;

            databaseMapping.AssertValid(throwOnError);

            return databaseMapping;
        }
Example #24
0
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException("contextType");
            }

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

            _activator = CreateActivator();

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

                var context = _activator();

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

                    _isConstructible = true;

                    PushConfiguration(context);

                    using (context)
                    {
                        ConfigureContext(context);

                        _connectionString       = context.InternalContext.Connection.ConnectionString;
                        _connectionStringName   = context.InternalContext.ConnectionStringName;
                        _connectionProviderName = context.InternalContext.ProviderName;
                        _connectionStringOrigin = context.InternalContext.ConnectionStringOrigin;
                    }
                }
            }
        }
Example #25
0
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo,
            Func <IDbDependencyResolver> resolver = null)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException("contextType");
            }

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

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

            _activator = CreateActivator();

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

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

                    using (context)
                    {
                        _connectionString =
                            DbInterception.Dispatch.Connection.GetConnectionString(
                                context.InternalContext.Connection,
                                new DbInterceptionContext().WithDbContext(context));
                        _connectionStringName   = context.InternalContext.ConnectionStringName;
                        _connectionProviderName = context.InternalContext.ProviderName;
                        _connectionStringOrigin = context.InternalContext.ConnectionStringOrigin;
                    }
                }
            }
        }
Example #26
0
        public static DbModel CreateModel(DbProviderInfo provider)
        {
            if (_chinookModel == null)
            {
                var builder = new DbModelBuilder();
                builder.Entity<Genre>();
                builder.Entity<MediaType>();
                builder.Entity<Artist>();
                builder.Entity<Album>();
                builder.Entity<Track>();
                builder.Entity<Employee>();
                builder.Entity<Customer>();
                builder.Entity<Invoice>();
                builder.Entity<InvoiceLine>();
                builder.Entity<Playlist>();
                builder.Entity<PlaylistTrack>();
                _chinookModel = builder.Build(provider);
            }

            return _chinookModel;
        }
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException("contextType");
            }

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

            _activator = CreateActivator();

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

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

                    PushConfiguration(context);

                    using (context)
                    {
                        ConfigureContext(context);

                        _connectionString       = context.InternalContext.Connection.ConnectionString;
                        _connectionStringName   = context.InternalContext.ConnectionStringName;
                        _connectionProviderName = context.InternalContext.ProviderName;
                        _connectionStringOrigin = context.InternalContext.ConnectionStringOrigin;
                    }
                }
            }
        }
Example #28
0
        private DbContextInfo(
            Type contextType,
            DbProviderInfo modelProviderInfo,
            AppConfig config,
            DbConnectionInfo connectionInfo,
            Func <IDbDependencyResolver> resolver = null)
        {
            if (!typeof(DbContext).IsAssignableFrom(contextType))
            {
                throw new ArgumentOutOfRangeException(nameof(contextType));
            }
            this._resolver          = resolver ?? (Func <IDbDependencyResolver>)(() => DbConfiguration.DependencyResolver);
            this._contextType       = contextType;
            this._modelProviderInfo = modelProviderInfo;
            this._appConfig         = config;
            this._connectionInfo    = connectionInfo;
            this._activator         = this.CreateActivator();
            if (this._activator == null)
            {
                return;
            }
            DbContext instance = this.CreateInstance();

            if (instance == null)
            {
                return;
            }
            this._isConstructible = true;
            using (instance)
            {
                this._connectionString       = DbInterception.Dispatch.Connection.GetConnectionString(instance.InternalContext.Connection, new DbInterceptionContext().WithDbContext(instance));
                this._connectionStringName   = instance.InternalContext.ConnectionStringName;
                this._connectionProviderName = instance.InternalContext.ProviderName;
                this._connectionStringOrigin = instance.InternalContext.ConnectionStringOrigin;
            }
        }
        public static DbModel GetDynamicUpdateModel(this DbContext context, DbProviderInfo providerInfo)
        {
            DebugCheck.NotNull(context);
            DebugCheck.NotNull(providerInfo);

            var model
                = context
                    .InternalContext
                    .CodeFirstModel
                    .CachedModelBuilder
                    .Build(providerInfo);

            var entityContainerMapping = model.DatabaseMapping.EntityContainerMappings.Single();

            entityContainerMapping
                .EntitySetMappings
                .Each(esm => esm.ClearModificationFunctionMappings());

            entityContainerMapping
                .AssociationSetMappings
                .Each(asm => asm.ModificationFunctionMapping = null);

            return model;
        }
Example #30
0
 /// <summary>
 /// Creates a new instance representing a given <see cref="T:System.Data.Entity.DbContext" /> type.  A <see cref="T:System.Data.Entity.Infrastructure.DbProviderInfo" />
 /// can be supplied in order to override the default determined provider used when constructing
 /// the underlying EDM model.
 /// </summary>
 /// <param name="contextType">
 /// The type deriving from <see cref="T:System.Data.Entity.DbContext" />.
 /// </param>
 /// <param name="modelProviderInfo">
 /// A <see cref="T:System.Data.Entity.Infrastructure.DbProviderInfo" /> specifying the underlying ADO.NET provider to target.
 /// </param>
 public DbContextInfo(Type contextType, DbProviderInfo modelProviderInfo)
     : this(Check.NotNull <Type>(contextType, nameof(contextType)), Check.NotNull <DbProviderInfo>(modelProviderInfo, nameof(modelProviderInfo)), AppConfig.DefaultInstance, (DbConnectionInfo)null, (Func <IDbDependencyResolver>)null)
 {
 }
Example #31
0
 private static DbProviderManifest GetProviderManifest(DbProviderInfo providerInfo)
 {
     return DbConfiguration.DependencyResolver.GetService<DbProviderFactory>(providerInfo.ProviderInvariantName)
         .GetProviderServices()
         .GetProviderManifest(providerInfo.ProviderManifestToken);
 }
Example #32
0
 private bool Equals(DbProviderInfo other)
 {
     return(string.Equals(_providerInvariantName, other._providerInvariantName) &&
            string.Equals(_providerManifestToken, other._providerManifestToken));
 }
Example #33
0
 /// <summary>
 /// Creates a new instance representing a given <see cref="T:System.Data.Entity.DbContext" /> type. An external config
 /// object (e.g. app.config or web.config) can be supplied and will be used during connection string
 /// resolution. This includes looking for connection strings and DefaultConnectionFactory entries.
 /// A <see cref="T:System.Data.Entity.Infrastructure.DbProviderInfo" /> can be supplied in order to override the default determined
 /// provider used when constructing the underlying EDM model. This can be useful to prevent EF from
 /// connecting to discover a manifest token.
 /// </summary>
 /// <param name="contextType">
 /// The type deriving from <see cref="T:System.Data.Entity.DbContext" />.
 /// </param>
 /// <param name="config"> An object representing the config file. </param>
 /// <param name="modelProviderInfo">
 /// A <see cref="T:System.Data.Entity.Infrastructure.DbProviderInfo" /> specifying the underlying ADO.NET provider to target.
 /// </param>
 public DbContextInfo(Type contextType, System.Configuration.Configuration config, DbProviderInfo modelProviderInfo)
     : this(Check.NotNull <Type>(contextType, nameof(contextType)), Check.NotNull <DbProviderInfo>(modelProviderInfo, nameof(modelProviderInfo)), new AppConfig(Check.NotNull <System.Configuration.Configuration>(config, nameof(config))), (DbConnectionInfo)null, (Func <IDbDependencyResolver>)null)
 {
 }
Example #34
0
 /// <summary>
 /// Creates a new instance representing a given <see cref="DbContext" /> type. An external config
 /// object (e.g. app.config or web.config) can be supplied and will be used during connection string
 /// resolution. This includes looking for connection strings and DefaultConnectionFactory entries.
 /// A <see cref="DbProviderInfo" /> can be supplied in order to override the default determined
 /// provider used when constructing the underlying EDM model. This can be useful to prevent EF from
 /// connecting to discover a manifest token.
 /// </summary>
 /// <param name="contextType">
 /// The type deriving from <see cref="DbContext" />.
 /// </param>
 /// <param name="config"> An object representing the config file. </param>
 /// <param name="modelProviderInfo">
 /// A <see cref="DbProviderInfo" /> specifying the underlying ADO.NET provider to target.
 /// </param>
 public DbContextInfo(Type contextType, Configuration config, DbProviderInfo modelProviderInfo)
     : this(
         Check.NotNull(contextType, "contextType"), Check.NotNull(modelProviderInfo, "modelProviderInfo"),
         new AppConfig(Check.NotNull(config, "config")), null)
 {
 }
Example #35
0
 internal DbModel(DbProviderInfo providerInfo, DbProviderManifest providerManifest)
 {
     this._databaseMapping = new DbDatabaseMapping().Initialize(EdmModel.CreateConceptualModel(3.0), EdmModel.CreateStoreModel(providerInfo, providerManifest, 3.0));
 }
Example #36
0
 /// <summary>
 /// Creates a new instance representing a given <see cref="DbContext" /> type.  A <see cref="DbProviderInfo" />
 /// can be supplied in order to override the default determined provider used when constructing
 /// the underlying EDM model.
 /// </summary>
 /// <param name="contextType">
 /// The type deriving from <see cref="DbContext" />.
 /// </param>
 /// <param name="modelProviderInfo">
 /// A <see cref="DbProviderInfo" /> specifying the underlying ADO.NET provider to target.
 /// </param>
 public DbContextInfo(Type contextType, DbProviderInfo modelProviderInfo)
     : this(
         Check.NotNull(contextType, "contextType"), Check.NotNull(modelProviderInfo, "modelProviderInfo"), AppConfig.DefaultInstance,
         null)
 {
 }
        internal static DbSpatialServices GetSpatialServices(IDbDependencyResolver resolver, EntityConnection connection)
        {
            DebugCheck.NotNull(resolver);
            DebugCheck.NotNull(connection);

            var storeItemCollection = (StoreItemCollection)connection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace);
            var key = new DbProviderInfo(
                storeItemCollection.StoreProviderInvariantName, storeItemCollection.StoreProviderManifestToken);

            return GetSpatialServices(resolver, key, () => GetProviderServices(connection.StoreConnection));
        }
        public DbSpatialServices GetSpatialServices(DbProviderInfo key)
        {
            DebugCheck.NotNull(key);

            return GetSpatialServices(_resolver.Value, key, () => this);
        }
        private static DbSpatialServices GetSpatialServices(
            IDbDependencyResolver resolver,
            DbProviderInfo key,
            Func<DbProviderServices> providerServices) // Delegate use to avoid lookup when not needed
        {
            DebugCheck.NotNull(resolver);
            DebugCheck.NotNull(key);
            DebugCheck.NotNull(providerServices);

            var services = _spatialServices.GetOrAdd(
                key,
                k =>
                resolver.GetService<DbSpatialServices>(k)
                ?? providerServices().GetSpatialServicesInternal(k.ProviderManifestToken, throwIfNotImplemented: false)
                ?? resolver.GetService<DbSpatialServices>());

            if (services == null)
            {
                throw new ProviderIncompatibleException(Strings.ProviderDidNotReturnSpatialServices);
            }
            return services;
        }
Example #40
0
        internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext)
            : base(null)
        {
            Contract.Requires(configuration != null);
            Contract.Requires(configuration.ContextType != null);

            _configuration = configuration;
            _calledByCreateDatabase = usersContext != null;

            // If DbContext CreateDatabase is using Migrations then the user has not opted out of initializers
            // and if we disable the initializer here then future calls to Initialize the database (for this or
            // a different connection) will fail. So only disable the initializer if Migrations are being used
            // explicitly.
            if (usersContext == null)
            {
                DisableInitializer(_configuration.ContextType);
            }

            if (_calledByCreateDatabase)
            {
                _usersContextInfo = new DbContextInfo(usersContext);
            }
            else
            {
                _usersContextInfo
                    = configuration.TargetDatabase == null
                          ? new DbContextInfo(configuration.ContextType)
                          : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase);

                if (!_usersContextInfo.IsConstructible)
                {
                    throw Error.ContextNotConstructible(configuration.ContextType);
                }
            }

            _modelDiffer = _configuration.ModelDiffer;

            var context = usersContext ?? _usersContextInfo.CreateInstance();
            try
            {
                _migrationAssembly
                    = new MigrationAssembly(_configuration.MigrationsAssembly, _configuration.MigrationsNamespace);

                _currentModel = context.GetModel();

                var connection = context.Database.Connection;

                _providerFactory = DbProviderServices.GetProviderFactory(connection);

                _defaultSchema = context.InternalContext.DefaultSchema;

                var historySchemas = GetHistorySchemas();

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

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

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

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

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

            _historyRepository.AppendHistoryModel(_currentModel, providerInfo);
        }