Beispiel #1
0
 public DatabaseExistenceState AnyModelTableExists(
     InternalContext internalContext)
 {
     if (!internalContext.DatabaseOperations.Exists(internalContext.Connection, internalContext.CommandTimeout, new Lazy <StoreItemCollection>((Func <StoreItemCollection>)(() => DatabaseTableChecker.CreateStoreItemCollection(internalContext)))))
     {
         return(DatabaseExistenceState.DoesNotExist);
     }
     using (ClonedObjectContext contextForDdlOps = internalContext.CreateObjectContextForDdlOps())
     {
         try
         {
             if (internalContext.CodeFirstModel == null)
             {
                 return(DatabaseExistenceState.Exists);
             }
             TableExistenceChecker service = DbConfiguration.DependencyResolver.GetService <TableExistenceChecker>((object)internalContext.ProviderName);
             if (service == null)
             {
                 return(DatabaseExistenceState.Exists);
             }
             List <EntitySet> list = this.GetModelTables(internalContext).ToList <EntitySet>();
             if (!list.Any <EntitySet>() || this.QueryForTableExistence(service, contextForDdlOps, list))
             {
                 return(DatabaseExistenceState.Exists);
             }
             return(internalContext.HasHistoryTableEntry() ? DatabaseExistenceState.Exists : DatabaseExistenceState.ExistsConsideredEmpty);
         }
         catch (Exception ex)
         {
             return(DatabaseExistenceState.Exists);
         }
     }
 }
        public virtual bool IsMigrationsConfigured(InternalContext internalContext, Func <bool> databaseExists)
        {
            DebugCheck.NotNull(internalContext);

            try
            {
                if (!_finder(internalContext))
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Debug.Fail("Exception ignored while attempting to create migration configuration: " + ex);
                return(false);
            }

            if (databaseExists())
            {
                return(true);
            }

            throw new InvalidOperationException(
                      Strings.DatabaseInitializationStrategy_MigrationsEnabled(internalContext.Owner.GetType().Name));
        }
Beispiel #3
0
        // <summary>
        // Creates a database using the core provider (i.e. ObjectContext.CreateDatabase) or
        // by using Code First Migrations <see cref="DbMigrator" /> to create an empty database
        // and the perform an automatic migration to the current model.
        // </summary>
        public virtual void CreateDatabase(
            InternalContext internalContext,
            Func <DbMigrationsConfiguration, DbContext, MigratorBase> createMigrator,
            ObjectContext objectContext)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(createMigrator);
            // objectContext may be null when testing.

            if (internalContext.CodeFirstModel != null &&
                _resolver.GetService <Func <MigrationSqlGenerator> >(internalContext.ProviderName) != null)
            {
                createMigrator(
                    internalContext.MigrationsConfiguration,
                    internalContext.Owner).Update();
            }
            else
            {
                internalContext.DatabaseOperations.Create(objectContext);
                internalContext.SaveMetadataToDatabase();
            }

            // If the database is created explicitly, then this is treated as overriding the
            // database initialization strategy, so make it as already run.
            internalContext.MarkDatabaseInitialized();
        }
        public DatabaseExistenceState AnyModelTableExists(InternalContext internalContext)
        {
            var exists = internalContext.DatabaseOperations.Exists(
                internalContext.Connection,
                internalContext.CommandTimeout,
                new Lazy <StoreItemCollection>(() => CreateStoreItemCollection(internalContext)));

            if (!exists)
            {
                return(DatabaseExistenceState.DoesNotExist);
            }

            using (var clonedObjectContext = internalContext.CreateObjectContextForDdlOps())
            {
                try
                {
                    if (internalContext.CodeFirstModel == null)
                    {
                        // If not Code First, then assume tables created in some other way
                        return(DatabaseExistenceState.Exists);
                    }

                    var checker = DbConfiguration.DependencyResolver.GetService <TableExistenceChecker>(internalContext.ProviderName);

                    if (checker == null)
                    {
                        // If we can't check for tables, then assume they exist as we did in older versions
                        return(DatabaseExistenceState.Exists);
                    }

                    var modelTables = GetModelTables(internalContext).ToList();

                    if (!modelTables.Any())
                    {
                        // If this is an empty model, then all tables that can exist (0) do exist
                        return(DatabaseExistenceState.Exists);
                    }

                    if (QueryForTableExistence(checker, clonedObjectContext, modelTables))
                    {
                        // If any table exists, then assume that this is a non-empty database
                        return(DatabaseExistenceState.Exists);
                    }

                    // At this point we know no model tables exist. If the history table exists and has an entry
                    // for this context, then treat this as a non-empty database, otherwise treat is as existing
                    // but empty.
                    return(internalContext.HasHistoryTableEntry()
                        ? DatabaseExistenceState.Exists
                        : DatabaseExistenceState.ExistsConsideredEmpty);
                }
                catch (Exception ex)
                {
                    Debug.Fail(ex.Message, ex.ToString());

                    // Revert to previous behavior on error
                    return(DatabaseExistenceState.Exists);
                }
            }
        }
Beispiel #5
0
        public virtual bool CompatibleWithModel(
            InternalContext internalContext,
            ModelHashCalculator modelHashCalculator,
            bool throwIfNoMetadata,
            DatabaseExistenceState existenceState = DatabaseExistenceState.Unknown)
        {
            if (internalContext.CodeFirstModel == null)
            {
                if (throwIfNoMetadata)
                {
                    throw Error.Database_NonCodeFirstCompatibilityCheck();
                }
                return(true);
            }
            VersionedModel model = internalContext.QueryForModel(existenceState);

            if (model != null)
            {
                return(internalContext.ModelMatches(model));
            }
            string a = internalContext.QueryForModelHash();

            if (a != null)
            {
                return(string.Equals(a, modelHashCalculator.Calculate(internalContext.CodeFirstModel), StringComparison.Ordinal));
            }
            if (throwIfNoMetadata)
            {
                throw Error.Database_NoDatabaseMetadata();
            }
            return(true);
        }
Beispiel #6
0
 public InternalEntityEntry(InternalContext internalContext, IEntityStateEntry stateEntry)
 {
     this._internalContext = internalContext;
     this._stateEntry      = stateEntry;
     this._entity          = stateEntry.Entity;
     this._entityType      = ObjectContextTypeCache.GetObjectType(this._entity.GetType());
 }
Beispiel #7
0
 internal InternalSqlNonSetQuery(
     InternalContext internalContext,
     Type elementType,
     string sql,
     object[] parameters)
     : this(internalContext, elementType, sql, new bool?(), parameters)
 {
 }
        /// <summary>
        ///     Initializes a new instance of the <see cref="DbDataRecordPropertyValues" /> class.
        /// </summary>
        /// <param name="internalContext"> The internal context. </param>
        /// <param name="type"> The type. </param>
        /// <param name="dataRecord"> The data record. </param>
        /// <param name="isEntity">
        ///     If set to <c>true</c> this is a dictionary for an entity, otherwise it is a dictionary for a complex object.
        /// </param>
        internal DbDataRecordPropertyValues(
            InternalContext internalContext, Type type, DbUpdatableDataRecord dataRecord, bool isEntity)
            : base(internalContext, type, isEntity)
        {
            DebugCheck.NotNull(dataRecord);

            _dataRecord = dataRecord;
        }
 private static StoreItemCollection CreateStoreItemCollection(InternalContext internalContext)
 {
     using (var clonedObjectContext = internalContext.CreateObjectContextForDdlOps())
     {
         var entityConnection = ((EntityConnection)clonedObjectContext.ObjectContext.Connection);
         return((StoreItemCollection)entityConnection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace));
     }
 }
Beispiel #10
0
 public EdmMetadataRepository(
     InternalContext usersContext,
     string connectionString,
     DbProviderFactory providerFactory)
     : base(usersContext, connectionString, providerFactory)
 {
     this._existingTransaction = usersContext.TryGetCurrentStoreTransaction();
 }
Beispiel #11
0
        private InternalSqlNonSetQuery(InternalContext internalContext, Type elementType, string sql, bool?streaming, object[] parameters)
            : base(sql, streaming, parameters)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(elementType);

            _internalContext = internalContext;
            _elementType     = elementType;
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="InternalPropertyValues" /> class.
        /// </summary>
        /// <param name="internalContext"> The internal context with which the entity of complex object is associated. </param>
        /// <param name="type"> The type of the entity or complex object. </param>
        /// <param name="isEntityValues">
        ///     If set to <c>true</c> this is a dictionary for an entity, otherwise it is a dictionary for a complex object.
        /// </param>
        protected InternalPropertyValues(InternalContext internalContext, Type type, bool isEntityValues)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(type);

            _internalContext = internalContext;
            _type            = type;
            _isEntityValues  = isEntityValues;
        }
Beispiel #13
0
 protected InternalPropertyValues(
     InternalContext internalContext,
     Type type,
     bool isEntityValues)
 {
     this._internalContext = internalContext;
     this._type            = type;
     this._isEntityValues  = isEntityValues;
 }
Beispiel #14
0
 internal DbDataRecordPropertyValues(
     InternalContext internalContext,
     Type type,
     DbUpdatableDataRecord dataRecord,
     bool isEntity)
     : base(internalContext, type, isEntity)
 {
     this._dataRecord = dataRecord;
 }
Beispiel #15
0
        protected RepositoryBase(InternalContext usersContext, string connectionString, DbProviderFactory providerFactory)
        {
            DebugCheck.NotNull(usersContext);
            DebugCheck.NotEmpty(connectionString);
            DebugCheck.NotNull(providerFactory);

            _usersContext     = usersContext;
            _connectionString = connectionString;
            _providerFactory  = providerFactory;
        }
Beispiel #16
0
 private InternalSqlNonSetQuery(
     InternalContext internalContext,
     Type elementType,
     string sql,
     bool?streaming,
     object[] parameters)
     : base(sql, streaming, parameters)
 {
     this._internalContext = internalContext;
     this._elementType     = elementType;
 }
        // <summary>
        // Initializes a new instance of the <see cref="InternalEntityEntry" /> class.
        // </summary>
        // <param name="internalContext"> The internal context. </param>
        // <param name="stateEntry"> The state entry. </param>
        public InternalEntityEntry(InternalContext internalContext, IEntityStateEntry stateEntry)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(stateEntry);
            Debug.Assert(stateEntry.Entity != null);

            _internalContext = internalContext;
            _stateEntry      = stateEntry;
            _entity          = stateEntry.Entity;
            _entityType      = ObjectContextTypeCache.GetObjectType(_entity.GetType());
        }
Beispiel #18
0
 public virtual IEnumerable <EntitySet> GetModelTables(
     InternalContext internalContext)
 {
     return(internalContext.ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.SSpace).GetItems <EntityContainer>().Single <EntityContainer>().BaseEntitySets.OfType <EntitySet>().Where <EntitySet>((Func <EntitySet, bool>)(s =>
     {
         if (s.MetadataProperties.Contains("Type"))
         {
             return (string)s.MetadataProperties["Type"].Value == "Tables";
         }
         return true;
     })));
 }
Beispiel #19
0
 public InternalEntityEntry(InternalContext internalContext, object entity)
 {
     this._internalContext = internalContext;
     this._entity          = entity;
     this._entityType      = ObjectContextTypeCache.GetObjectType(this._entity.GetType());
     this._stateEntry      = this._internalContext.GetStateEntry(entity);
     if (this._stateEntry != null)
     {
         return;
     }
     this._internalContext.Set(this._entityType).InternalSet.Initialize();
 }
Beispiel #20
0
        protected RepositoryBase(
            InternalContext usersContext,
            string connectionString,
            DbProviderFactory providerFactory)
        {
            DbConnection connection = usersContext.Connection;

            if (connection != null && connection.State == ConnectionState.Open)
            {
                this._existingConnection = connection;
            }
            this._connectionString = connectionString;
            this._providerFactory  = providerFactory;
        }
Beispiel #21
0
        protected RepositoryBase(InternalContext usersContext, string connectionString, DbProviderFactory providerFactory)
        {
            DebugCheck.NotNull(usersContext);
            DebugCheck.NotEmpty(connectionString);
            DebugCheck.NotNull(providerFactory);

            var existingConnection = usersContext.Connection;

            if (existingConnection != null)
            {
                _existingConnection = existingConnection;
            }

            _connectionString = connectionString;
            _providerFactory  = providerFactory;
        }
Beispiel #22
0
 private void UpdateEntitySetMappingsForType(Type entityType)
 {
     if (this.TryUpdateEntitySetMappingsForType(entityType))
     {
         return;
     }
     if (this.IsComplexType(entityType))
     {
         throw Error.DbSet_DbSetUsedWithComplexType((object)entityType.Name);
     }
     if (InternalContext.IsPocoTypeInNonPocoAssembly(entityType))
     {
         throw Error.DbSet_PocoAndNonPocoMixedInSameAssembly((object)entityType.Name);
     }
     throw Error.DbSet_EntityTypeNotInModel((object)entityType.Name);
 }
Beispiel #23
0
 public virtual void CreateDatabase(
     InternalContext internalContext,
     Func <DbMigrationsConfiguration, DbContext, MigratorBase> createMigrator,
     ObjectContext objectContext)
 {
     if (internalContext.CodeFirstModel != null && this._resolver.GetService <Func <MigrationSqlGenerator> >((object)internalContext.ProviderName) != null)
     {
         createMigrator(internalContext.MigrationsConfiguration, internalContext.Owner).Update();
     }
     else
     {
         internalContext.DatabaseOperations.Create(objectContext);
         internalContext.SaveMetadataToDatabase();
     }
     internalContext.MarkDatabaseInitialized();
 }
Beispiel #24
0
        public static PropertyEntryMetadata ValidateNameAndGetMetadata(
            InternalContext internalContext,
            Type declaringType,
            Type requestedType,
            string propertyName)
        {
            Type type;

            DbHelpers.GetPropertyTypes(declaringType).TryGetValue(propertyName, out type);
            MetadataWorkspace metadataWorkspace = internalContext.ObjectContext.MetadataWorkspace;
            StructuralType    structuralType    = metadataWorkspace.GetItem <StructuralType>(declaringType.FullNameWithNesting(), DataSpace.OSpace);
            bool      isMapped  = false;
            bool      isComplex = false;
            EdmMember edmMember;

            structuralType.Members.TryGetValue(propertyName, false, out edmMember);
            if (edmMember != null)
            {
                EdmProperty edmProperty = edmMember as EdmProperty;
                if (edmProperty == null)
                {
                    return((PropertyEntryMetadata)null);
                }
                if (type == (Type)null)
                {
                    PrimitiveType edmType = edmProperty.TypeUsage.EdmType as PrimitiveType;
                    type = edmType == null ? ((ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace)).GetClrType((StructuralType)edmProperty.TypeUsage.EdmType) : edmType.ClrEquivalentType;
                }
                isMapped  = true;
                isComplex = edmProperty.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType;
            }
            else
            {
                IDictionary <string, Func <object, object> >   propertyGetters = DbHelpers.GetPropertyGetters(declaringType);
                IDictionary <string, Action <object, object> > propertySetters = DbHelpers.GetPropertySetters(declaringType);
                if (!propertyGetters.ContainsKey(propertyName) && !propertySetters.ContainsKey(propertyName))
                {
                    return((PropertyEntryMetadata)null);
                }
            }
            if (!requestedType.IsAssignableFrom(type))
            {
                throw Error.DbEntityEntry_WrongGenericForProp((object)propertyName, (object)declaringType.Name, (object)requestedType.Name, (object)type.Name);
            }
            return(new PropertyEntryMetadata(declaringType, type, propertyName, isMapped, isComplex));
        }
Beispiel #25
0
        public static DbMigrationsConfiguration GetMigrationsConfiguration(InternalContext internalContext)
        {
            DebugCheck.NotNull(internalContext);

            var contextType = internalContext.Owner.GetType();

            return(new DbMigrationsConfiguration
            {
                ContextType = contextType,
                AutomaticMigrationsEnabled = true,
                MigrationsAssembly = contextType.Assembly,
                MigrationsNamespace = contextType.Namespace,
                ContextKey = internalContext.ContextKey,
                TargetDatabase = new DbConnectionInfo(internalContext.OriginalConnectionString, internalContext.ProviderName),
                CommandTimeout = internalContext.CommandTimeout
            });
        }
        // <summary>
        // Initializes a new instance of the <see cref="InternalEntityEntry" /> class for an
        // entity which may or may not be attached to the context.
        // </summary>
        // <param name="internalContext"> The internal context. </param>
        // <param name="entity"> The entity. </param>
        public InternalEntityEntry(InternalContext internalContext, object entity)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(entity);

            _internalContext = internalContext;
            _entity          = entity;
            _entityType      = ObjectContextTypeCache.GetObjectType(_entity.GetType());

            _stateEntry = _internalContext.GetStateEntry(entity);
            if (_stateEntry == null)
            {
                // This will cause the context and model to be initialized and will throw an exception
                // if the entity type is not part of the model.
                _internalContext.Set(_entityType).InternalSet.Initialize();
            }
        }
Beispiel #27
0
 internal DbLocalView(InternalContext internalContext)
 {
     this._internalContext = internalContext;
     try
     {
         this._inStateManagerChanged = true;
         foreach (TEntity localEntity in this._internalContext.GetLocalEntities <TEntity>())
         {
             this.Add(localEntity);
         }
     }
     finally
     {
         this._inStateManagerChanged = false;
     }
     this._internalContext.RegisterObjectStateManagerChangedEvent(new CollectionChangeEventHandler(this.StateManagerChangedHandler));
 }
        public virtual bool CompatibleWithModel(
            InternalContext internalContext, ModelHashCalculator modelHashCalculator,
            bool throwIfNoMetadata, DatabaseExistenceState existenceState = DatabaseExistenceState.Unknown)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(modelHashCalculator);

            if (internalContext.CodeFirstModel == null)
            {
                if (throwIfNoMetadata)
                {
                    throw Error.Database_NonCodeFirstCompatibilityCheck();
                }
                return(true);
            }

            var model = internalContext.QueryForModel(existenceState);

            if (model != null)
            {
                return(internalContext.ModelMatches(model));
            }

            // Migrations history was not found in the database so fall back to doing a model hash compare
            // to deal with databases created using EF 4.1 and 4.2.
            var databaseModelHash = internalContext.QueryForModelHash();

            if (databaseModelHash == null)
            {
                if (throwIfNoMetadata)
                {
                    throw Error.Database_NoDatabaseMetadata();
                }
                return(true);
            }

            return(String.Equals(
                       databaseModelHash, modelHashCalculator.Calculate(internalContext.CodeFirstModel),
                       StringComparison.Ordinal));
        }
Beispiel #29
0
        /// <summary>
        ///     Creates a database using the core provider (i.e. ObjectContext.CreateDatabase) or
        ///     by using Code First Migrations <see cref="DbMigrator" /> to create an empty database
        ///     and the perform an automatic migration to the current model.
        ///     Migrations is used if Code First is being used and the EF provider is for SQL Server
        ///     or SQL Compact. The core is used for non-Code First models and for other providers even
        ///     when using Code First.
        /// </summary>
        public virtual void CreateDatabase(
            InternalContext internalContext,
            Func <DbMigrationsConfiguration, DbContext, MigratorBase> createMigrator,
            ObjectContext objectContext)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(createMigrator);
            // objectContext may be null when testing.

            if (internalContext.CodeFirstModel != null &&
                _resolver.GetService <MigrationSqlGenerator>(internalContext.ProviderName) != null)
            {
                var contextType = internalContext.Owner.GetType();

                var migrator = createMigrator(
                    new DbMigrationsConfiguration
                {
                    ContextType = contextType,
                    AutomaticMigrationsEnabled = true,
                    MigrationsAssembly         = contextType.Assembly,
                    MigrationsNamespace        = contextType.Namespace,
                    ContextKey     = internalContext.ContextKey,
                    TargetDatabase =
                        new DbConnectionInfo(
                            internalContext.OriginalConnectionString, internalContext.ProviderName)
                },
                    internalContext.Owner);

                migrator.Update();
            }
            else
            {
                internalContext.DatabaseOperations.Create(objectContext);
                internalContext.SaveMetadataToDatabase();
            }

            // If the database is created explicitly, then this is treated as overriding the
            // database initialization strategy, so make it as already run.
            internalContext.MarkDatabaseInitialized();
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="DbLocalView{TEntity}" /> class for entities
        ///     of the given generic type in the given internal context.
        /// </summary>
        /// <param name="internalContext"> The internal context. </param>
        internal DbLocalView(InternalContext internalContext)
        {
            DebugCheck.NotNull(internalContext);

            _internalContext = internalContext;

            try
            {
                // Set a flag to prevent changes we're making to the ObservableCollection based on the
                // contents of the state manager from being pushed back to the state manager.
                _inStateManagerChanged = true;
                foreach (var entity in _internalContext.GetLocalEntities <TEntity>())
                {
                    Add(entity);
                }
            }
            finally
            {
                _inStateManagerChanged = false;
            }

            _internalContext.RegisterObjectStateManagerChangedEvent(StateManagerChangedHandler);
        }