コード例 #1
0
 /// <summary>
 /// Constructs a new context instance around an existing ObjectContext.
 /// </summary>
 /// <param name="objectContext"> An existing ObjectContext to wrap with the new context. </param>
 /// <param name="dbContextOwnsObjectContext">
 ///     If set to <c>true</c> the ObjectContext is disposed when the DbContext is disposed, otherwise the caller must dispose the connection.
 /// </param>
 public DbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
 {
     Check.NotNull <ObjectContext>(objectContext, nameof(objectContext));
     DbConfigurationManager.Instance.EnsureLoadedForContext(this.GetType());
     this._internalContext = (InternalContext) new EagerInternalContext(this, objectContext, dbContextOwnsObjectContext);
     this.DiscoverAndInitializeSets();
 }
コード例 #2
0
        private void ChangeStateToModifiedIfApplicable(T entity)
        {
            if (entity.IsTransientRecord())
            {
                return;
            }

            var entry = InternalContext.Entry(entity);

            if (entry.State == EfState.Detached)
            {
                // Entity was detached before or was explicitly constructed.
                // This unfortunately sets all properties to modified.
                entry.State = EfState.Modified;
            }
            else if (entry.State == EfState.Unchanged)
            {
                // We simply do nothing here, because it is ensured now that DetectChanges()
                // gets implicitly called prior SaveChanges().

                //if (this.AutoCommitEnabledInternal && !ctx.Configuration.AutoDetectChangesEnabled)
                //{
                //	_context.DetectChanges();
                //}
            }
        }
コード例 #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)
            {
                if (!_migrationsChecker.IsMigrationsConfigured(internalContext, () => false))
                {
                    var migrator = createMigrator(
                        GetMigrationsConfiguration(internalContext),
                        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();
        }
コード例 #4
0
        /// <summary>
        ///     Finds an entity with the given primary key values.
        ///     If an entity with the given primary key values exists in the context, then it is
        ///     returned immediately without making a request to the store.  Otherwise, a request
        ///     is made to the store for an entity with the given primary key values and this entity,
        ///     if found, is attached to the context and returned.  If no entity is found in the
        ///     context or the store, then null is returned.
        /// </summary>
        /// <remarks>
        ///     The ordering of composite key values is as defined in the EDM, which is in turn as defined in
        ///     the designer, by the Code First fluent API, or by the DataMember attribute.
        /// </remarks>
        /// <param name="keyValues"> The values of the primary key for the entity to be found. </param>
        /// <returns> The entity found, or null. </returns>
        /// <exception cref="InvalidOperationException">Thrown if multiple entities exist in the context with the primary key values given.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the type of entity is not part of the data model for this context.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the types of the key values do not match the types of the key values for the entity type to be found.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the context has been disposed.</exception>
        public TEntity Find(params object[] keyValues)
        {
            InternalContext.ObjectContext.AsyncMonitor.EnsureNotEntered();

            // This DetectChanges is useful in the case where objects are added to the graph and then the user
            // attempts to find one of those added objects.
            InternalContext.DetectChanges();

            var key = new WrappedEntityKey(EntitySet, EntitySetName, keyValues, "keyValues");

            // First, check for the entity in the state manager.  This includes first checking
            // for non-Added objects that match the key.  If the entity was not found, then
            // we check for Added objects.  We don't just use GetObjectByKey
            // because it would go to the store before checking for Added objects, and also
            // because if the object found was of the wrong type then it would still get into
            // the state manager.
            var entity = FindInStateManager(key) ?? FindInStore(key, "keyValues");

            if (entity != null &&
                !(entity is TEntity))
            {
                throw Error.DbSet_WrongEntityTypeFound(entity.GetType().Name, typeof(TEntity).Name);
            }
            return((TEntity)entity);
        }
コード例 #5
0
        /// <summary>
        /// 尝试创建对应的表。
        /// </summary>
        /// <param name="entityType">实体类型。</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool TryCreate(Type entityType, InternalContext context)
        {
            var metadata = EntityMetadataUnity.GetEntityMetadata(entityType);

            var lazy = new Lazy <bool>(() =>
            {
                var syntax = context.Database.Provider.GetService <ISyntaxProvider>();

                //判断表是否存在
                SqlCommand sql = syntax.ExistsTable(metadata.TableName);
                if (context.Database.ExecuteScalar <int>(sql) == 0)
                {
                    if (InternalCreate(metadata, syntax, context))
                    {
                        //通知 context 仓储已经创建
                        if (context.OnRespositoryCreated != null)
                        {
                            context.OnRespositoryCreated(entityType);
                        }

                        return(true);
                    }

                    return(false);
                }

                return(true);
            });

            return(cache.TryGetValue(entityType, () => lazy.Value));
        }
コード例 #6
0
        public void Update(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (this.AutoCommitEnabled)
            {
                if (!InternalContext.Configuration.AutoDetectChangesEnabled)
                {
                    InternalContext.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                }
                _context.SaveChanges();
            }
            else
            {
                try
                {
                    this.Entities.Attach(entity);
                    InternalContext.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                }
                finally { }
            }
        }
コード例 #7
0
        public override PropertyValue GetValue(IEntity entity, IProperty property)
        {
            var entityProperty = property.As <EntityProperty>();

            var instanceName = GetInstanceName(entity, entityProperty.RelationType);
            var environment  = GetEnvironment(entity);

            using (var context = new InternalContext(instanceName))
            {
                context.As <IEntityPersistentEnvironment>(s => s.Environment        = environment);
                context.As <IEntityPersistentInstanceContainer>(s => s.InstanceName = instanceName);

                var provider   = context.CreateRepositoryProvider(entityProperty.RelationType);
                var expression = BuidRelationExpression(entity, entityProperty);
                if (expression != null)
                {
                    var value = Execute(provider.Queryable, expression);

                    //设置实体所属的实体Owner
                    value.As <IEntityRelation>(e => e.Owner = new EntityOwner(entity, property));

                    return(value == null ? PropertyValue.Empty : PropertyValue.NewValue(value));
                }

                return(PropertyValue.Empty);
            }
        }
コード例 #8
0
ファイル: EfRepository.cs プロジェクト: war-man/saas-nlp
        public void Delete(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (InternalContext.Entry(entity).State == System.Data.Entity.EntityState.Detached)
            {
                T attachedEntity = Local.SingleOrDefault(e => e.Id == entity.Id);      // You need to have access to key
                if (attachedEntity != null)
                {
                    var attachedEntry = InternalContext.Entry(attachedEntity);
                    attachedEntry.CurrentValues.SetValues(entity);
                }
                else
                {
                    this.Entities.Attach(entity);
                }
            }

            this.Entities.Remove(entity);

            if (this.AutoCommitEnabledInternal)
            {
                _context.SaveChanges();
            }
            else
            {
                _context.SaveChanges();
            }
        }
コード例 #9
0
        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));
        }
コード例 #10
0
        /// <summary>
        /// 尝试创建对应的表。
        /// </summary>
        /// <param name="entityType">实体类型。</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool TryCreate(Type entityType, InternalContext context, Action <Type> succeed, Action <Type, Exception> failed)
        {
            var metadata = EntityMetadataUnity.GetEntityMetadata(entityType);

            var lazy = new Lazy <bool>(() =>
            {
                var service = context.Database.Provider.GetTableGenerateProvider();
                if (service == null || service.IsExists(context.Database, entityType))
                {
                    return(true);
                }

                try
                {
                    service.TryCreate(context.Database, entityType);

                    //通知 context 仓储已经创建
                    succeed?.Invoke(entityType);

                    return(true);
                }
                catch (Exception exp)
                {
                    failed?.Invoke(entityType, exp);
                    return(false);
                }
            });

            var cacheKey = string.Format("{0}:{1}", context.InstanceName, entityType.FullName);

            return(cache.GetOrAdd(cacheKey, key => lazy.Value));
        }
コード例 #11
0
        private void IterateOverGraph(Action <DatasetViewGraph, DatasetFacade, DatasetFacade> action)
        {
            var root = m_Project.Root();

            action(m_Graph, null, root);

            var nodes = new Queue <DatasetFacade>();

            nodes.Enqueue(root);
            while (nodes.Count > 0)
            {
                var dataset = nodes.Dequeue();
                foreach (var child in dataset.Children())
                {
                    var temp = child;
                    if (InternalContext.IsSynchronized)
                    {
                        action(m_Graph, dataset, temp);
                    }
                    else
                    {
                        Action a = () => action(m_Graph, dataset, temp);
                        InternalContext.Invoke(a);
                    }

                    nodes.Enqueue(child);
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="autoLog"></param>
        /// <param name="logAction"></param>
        /// <returns></returns>
        public IEntityLogInfo <T> Update(T entity, bool autoLog = true, string logAction = null)
        {
            Guard.ArgumentNotNull(() => entity);
            if (entity is BaseDataEntity)
            {
                (entity as BaseDataEntity).LastUpdatedOn = DateTime.Now;
            }
            var logInfo = CreateEntityLogInfo(EntityLogActionType.Update, entity, false, logAction);

            if (this.AutoCommitEnabled)
            {
                DbContext.SaveChanges();
            }
            else
            {
                try
                {
                    this.Entities.Attach(entity);
                    InternalContext.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                }
                finally { }
            }
            if (autoLog && _autoUpdateEntityLog)
            {
                logInfo.Update(this.AutoCommitEnabled);
            }
            return(logInfo);
        }
コード例 #13
0
        public override PropertyValue GetValue(IEntity entity, IProperty property)
        {
            var entityProperty = property.As <EntitySetProperty>();
            var instanceName   = GetInstanceName(entity, entityProperty.RelationType);
            var environment    = GetEnvironment(entity);

            using (var context = new InternalContext(instanceName))
            {
                context.Environment  = environment;
                context.InstanceName = instanceName;

                var    provider   = context.CreateRepositoryProvider(entityProperty.RelationType);
                var    expression = BuidRelationExpression(entity, entityProperty);
                object result     = null;
                if (expression != null)
                {
                    result = Execute(provider.Queryable, expression);
                    var querySetType = typeof(EntitySet <>).MakeGenericType(entityProperty.RelationType);
                    var list         = querySetType.New(new[] { result });

                    //设置实体集所属的实体Owner
                    list.As <IEntityRelation>(e => e.Owner = new EntityOwner(entity, property));

                    return(PropertyValueHelper.NewValue(list));
                }

                return(PropertyValueHelper.NewValue(result));
            }
        }
コード例 #14
0
 /// <summary>
 /// 初始化。
 /// </summary>
 protected virtual void Initialize()
 {
     context = new InternalContext(configName);
     context.OnRespositoryCreated = new Action <Type>(t =>
     {
     });
 }
コード例 #15
0
        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;
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// Uses Code First with the given context and writes the resulting Entity Data Model to the given
        /// writer in EDMX form.  This method can only be used with context instances that use Code First
        /// and create the model internally.  The method cannot be used for contexts created using Database
        /// First or Model First, for contexts created using a pre-existing <see cref="T:System.Data.Entity.Core.Objects.ObjectContext" />, or
        /// for contexts created using a pre-existing <see cref="T:System.Data.Entity.Infrastructure.DbCompiledModel" />.
        /// </summary>
        /// <param name="context"> The context. </param>
        /// <param name="writer"> The writer. </param>
        public static void WriteEdmx(DbContext context, XmlWriter writer)
        {
            Check.NotNull <DbContext>(context, nameof(context));
            Check.NotNull <XmlWriter>(writer, nameof(writer));
            InternalContext internalContext = context.InternalContext;

            if (internalContext is EagerInternalContext)
            {
                throw Error.EdmxWriter_EdmxFromObjectContextNotSupported();
            }
            DbModel beingInitialized = internalContext.ModelBeingInitialized;

            if (beingInitialized != null)
            {
                EdmxWriter.WriteEdmx(beingInitialized, writer);
            }
            else
            {
                DbCompiledModel codeFirstModel = internalContext.CodeFirstModel;
                if (codeFirstModel == null)
                {
                    throw Error.EdmxWriter_EdmxFromModelFirstNotSupported();
                }
                DbModelBuilder dbModelBuilder = codeFirstModel.CachedModelBuilder.Clone();
                EdmxWriter.WriteEdmx(internalContext.ModelProviderInfo == null ? dbModelBuilder.Build(internalContext.Connection) : dbModelBuilder.Build(internalContext.ModelProviderInfo), writer);
            }
        }
コード例 #17
0
        /// <summary>
        ///     Creates a new internal query based on the information in an existing query together with
        ///     a new underlying ObjectQuery.
        /// </summary>
        public InternalQuery(InternalContext internalContext, ObjectQuery objectQuery)
        {
            DebugCheck.NotNull(internalContext);

            _internalContext = internalContext;
            _objectQuery     = (ObjectQuery <TElement>)objectQuery;
        }
コード例 #18
0
        /// <summary>
        /// 尝试创建对应的表。
        /// </summary>
        /// <param name="entityType">实体类型。</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool TryCreate(Type entityType, InternalContext context)
        {
            var metadata = EntityMetadataUnity.GetEntityMetadata(entityType);

            var lazy = new Lazy <bool>(() =>
            {
                var syntax = context.Database.Provider.GetService <ISyntaxProvider>();

                //判断表是否存在
                SqlCommand sql = syntax.ExistsTable(metadata.TableName);
                if (context.Database.ExecuteScalar <int>(sql) == 0)
                {
                    if (InternalCreate(metadata, syntax, context))
                    {
                        //通知 context 仓储已经创建
                        context.OnRespositoryCreated?.Invoke(entityType);

                        return(true);
                    }

                    return(false);
                }

                return(true);
            });

            var cacheKey = string.Format("{0}:{1}", context.InstanceName, entityType.FullName);

            return(cache.GetOrAdd(cacheKey, key => lazy.Value));
        }
コード例 #19
0
 private static StoreItemCollection CreateStoreItemCollection(InternalContext internalContext)
 {
     using (var clonedObjectContext = internalContext.CreateObjectContextForDdlOps())
     {
         var entityConnection = ((EntityConnection)clonedObjectContext.ObjectContext.Connection);
         return (StoreItemCollection)entityConnection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace);
     }
 }
コード例 #20
0
ファイル: DbQueryProvider.cs プロジェクト: dotnet/ef6tools
        // <summary>
        // Creates a provider that wraps the given provider.
        // </summary>
        // <param name="internalQuery"> The internal query to wrap. </param>
        public DbQueryProvider(InternalContext internalContext, IInternalQuery internalQuery)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(internalQuery);

            _internalContext = internalContext;
            _internalQuery   = internalQuery;
        }
コード例 #21
0
        /// <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="isEntityValues">
        ///     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;
        }
コード例 #22
0
 internal virtual void InitializeLazyInternalContext(
     IInternalConnection internalConnection,
     DbCompiledModel model = null)
 {
     DbConfigurationManager.Instance.EnsureLoadedForContext(this.GetType());
     this._internalContext = (InternalContext) new LazyInternalContext(this, internalConnection, model, DbConfiguration.DependencyResolver.GetService <Func <DbContext, IDbModelCacheKey> >(), DbConfiguration.DependencyResolver.GetService <AttributeProvider>(), (Lazy <DbDispatchers>)null, (ObjectContext)null);
     this.DiscoverAndInitializeSets();
 }
コード例 #23
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed && disposing)
     {
         Debug.WriteLine(string.Format("ContextCacheDispose({0})", _configHash));
         _currentContext = null;
     }
 }
コード例 #24
0
 public EntityPersister(InternalContext context)
 {
     this.context        = context;
     Database            = context.Database;
     entityQueryProvider = new EntityQueryProvider(context);
     queryable           = new QueryProvider(entityQueryProvider);
     environment         = context.Environment;
 }
コード例 #25
0
ファイル: DbContext.cs プロジェクト: jwanagel/jjwtest
        /// <summary>
        ///     Initializes the internal context, discovers and initializes sets, and initializes from a model if one is provided.
        /// </summary>
        private void InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model = null)
        {
            DbConfigurationManager.Instance.EnsureLoadedForContext(GetType());

            _internalContext = new LazyInternalContext(
                this, internalConnection, model, DbConfiguration.GetService <IDbModelCacheKeyFactory>());
            DiscoverAndInitializeSets();
        }
コード例 #26
0
        /// <summary>
        ///     Returns an <see cref="IDbAsyncEnumerator{TElement}" /> which when enumerated will execute the query against the database.
        /// </summary>
        /// <returns> The query results. </returns>
        public virtual IDbAsyncEnumerator <TElement> GetAsyncEnumerator()
        {
            Debug.Assert(_objectQuery != null, "InternalQuery should have been initialized.");

            InternalContext.Initialize();

            return(((IDbAsyncEnumerable <TElement>)_objectQuery).GetAsyncEnumerator());
        }
コード例 #27
0
 /// <summary>
 /// 使用 <see cref="IDatabase"/> 对象初始化 <see cref="T:Lord.Data.Entity.EntityPersister`1"/> 类的新实例。
 /// </summary>
 /// <param name="database">一个 <see cref="IDatabase"/> 对象。</param>
 public EntityPersister(IDatabase database)
 {
     Database            = database;
     context             = new InternalContext(database);
     entityQueryProvider = new EntityQueryProvider(context);
     queryable           = new QueryProvider(entityQueryProvider);
     environment         = context.Environment;
 }
コード例 #28
0
        /// <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 = "isEntityValues">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)
        {
            Contract.Requires(dataRecord != null);

            _dataRecord = dataRecord;
        }
コード例 #29
0
        /// <summary>
        ///     Creates a provider that wraps the given provider.
        /// </summary>
        /// <param name="provider"> The provider to wrap. </param>
        public DbQueryProvider(InternalContext internalContext, ObjectQueryProvider provider)
        {
            DebugCheck.NotNull(internalContext);
            DebugCheck.NotNull(provider);

            _internalContext = internalContext;
            _provider        = provider;
        }
コード例 #30
0
 /// <summary>
 /// 初始化。
 /// </summary>
 private void Initialize(EntityContextOptions options)
 {
     context = new InternalContext(options)
     {
         OnRespositoryCreated      = OnRespositoryCreated,
         OnRespositoryCreateFailed = OnRespositoryCreateFailed
     };
 }
コード例 #31
0
        // <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;
        }
コード例 #32
0
        /// <summary>
        /// 初始化 <see cref="DefaultRepositoryProvider"/> 类的新实例。
        /// </summary>
        /// <param name="context"></param>
        public DefaultRepositoryProvider(InternalContext context)
        {
            this.context = context;
            var entityQueryProvider = new EntityQueryProvider(context);

            context.As <IEntityPersistentInstanceContainer>(s => entityQueryProvider.InitializeInstanceName(s.InstanceName));
            QueryProvider = new QueryProvider(entityQueryProvider);
            Queryable     = new QuerySet <TEntity>(QueryProvider, null);
        }
コード例 #33
0
ファイル: EfRepository.cs プロジェクト: Piligrem/MyWeb
        private void SetEntityStateToModifiedIfApplicable(T entity)
        {
            var entry = InternalContext.Entry(entity);

            if (entry.State == System.Data.Entity.EntityState.Detached || (this.AutoCommitEnabledInternal && !InternalContext.Configuration.AutoDetectChangesEnabled))
            {
                entry.State = System.Data.Entity.EntityState.Modified;
            }
        }
コード例 #34
0
        public virtual void AddRange(IEnumerable entities)
        {
            DebugCheck.NotNull(entities);

            InternalContext.DetectChanges();

            ActOnSet(
                entity => InternalContext.ObjectContext.AddObject(EntitySetName, entity), EntityState.Added, entities, "AddRange");
        }
コード例 #35
0
 /// <summary>
 /// 初始化 <see cref="EntityTreeRepository&lt;TEntity&gt;"/> 类的新实例。
 /// </summary>
 /// <param name="repository"></param>
 /// <param name="context"></param>
 public EntityTreeRepository(EntityRepository <TEntity> repository, InternalContext context)
 {
     this.repository = repository;
     entityType      = typeof(TEntity);
     metadata        = EntityMetadataUnity.GetEntityMetadata(entityType);
     metaTree        = metadata.EntityTree;
     database        = context.Database;
     syntax          = database.Provider.GetService <ISyntaxProvider>();
 }
コード例 #36
0
        private static void SetInternalNodeName()
        {
            PropertyInfo internalProperty = typeof(TelemetryContext).GetProperty("Internal",
                                                                                 BindingFlags.NonPublic | BindingFlags.Instance);

            InternalContext internalContext = (InternalContext)internalProperty.GetValue(Tc.Context);

            internalContext.NodeName = Tc.Context.User.Id;
        }
コード例 #37
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;
        }
コード例 #38
0
        /// <summary>
        /// Constructs a new context instance around an existing ObjectContext.
        /// </summary>
        /// <param name="objectContext"> An existing ObjectContext to wrap with the new context. </param>
        /// <param name="dbContextOwnsObjectContext">
        ///     If set to <c>true</c> the ObjectContext is disposed when the DbContext is disposed, otherwise the caller must dispose the connection.
        /// </param>
        public DbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
        {
            Check.NotNull(objectContext, "objectContext");

            DbConfigurationManager.Instance.EnsureLoadedForContext(GetType());

            _internalContext = new EagerInternalContext(this, objectContext, dbContextOwnsObjectContext);
            DiscoverAndInitializeSets();
        }
コード例 #39
0
        /// <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)
        {
            Contract.Requires(internalContext != null);
            Contract.Requires(type != null);

            _internalContext = internalContext;
            _type = type;
            _isEntityValues = isEntityValues;
        }
コード例 #40
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="InternalSqlNonSetQuery" /> class.
        /// </summary>
        /// <param name="internalContext"> The internal context. </param>
        /// <param name="elementType"> Type of the element. </param>
        /// <param name="sql"> The SQL. </param>
        /// <param name="parameters"> The parameters. </param>
        internal InternalSqlNonSetQuery(
            InternalContext internalContext, Type elementType, string sql, object[] parameters)
            : base(sql, parameters)
        {
            Contract.Requires(internalContext != null);
            Contract.Requires(elementType != null);

            _internalContext = internalContext;
            _elementType = elementType;
        }
コード例 #41
0
        /// <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)
        {
            //Contract.Requires(internalContext != null);
            //Contract.Requires(stateEntry != null);
            Contract.Assert(stateEntry.Entity != null);

            _internalContext = internalContext;
            _stateEntry = stateEntry;
            _entity = stateEntry.Entity;
            _entityType = ObjectContextTypeCache.GetObjectType(_entity.GetType());
        }
コード例 #42
0
        /// <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());
        }
コード例 #43
0
        /// <summary>
        ///     Initializes a new instance of the <see cref = "DbUpdateException" /> class.
        /// </summary>
        /// <param name = "internalContext">The internal context.</param>
        /// <param name = "innerException">The inner exception.</param>
        internal DbUpdateException(
            InternalContext internalContext, UpdateException innerException, bool involvesIndependentAssociations)
            : base(
                involvesIndependentAssociations
                    ? Strings.DbContext_IndependentAssociationUpdateException
                    : innerException.Message,
                innerException)
        {
            _internalContext = internalContext;
            _state.InvolvesIndependentAssociations = involvesIndependentAssociations;

            SubscribeToSerializeObjectState();
        }
コード例 #44
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;
        }
コード例 #45
0
        /// <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)
        {
            //Contract.Requires(internalContext != null);
            //Contract.Requires(entity != null);

            _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();
            }
        }
コード例 #46
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
                };
        }
コード例 #47
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)
        {
            //Contract.Requires(internalContext != null);
            //Contract.Requires(createMigrator != null);
            // objectContext may be null when testing.

            var sqlGenerator = _resolver.Value.GetService<MigrationSqlGenerator>(internalContext.ProviderName);

            if (internalContext.CodeFirstModel != null
                && sqlGenerator != null)
            {
                var contextType = internalContext.Owner.GetType();

                var migrator = createMigrator(
                    new DbMigrationsConfiguration
                        {
                            ContextType = contextType,
                            AutomaticMigrationsEnabled = true,
                            MigrationsAssembly = contextType.Assembly,
                            MigrationsNamespace = contextType.Namespace,
                            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();
        }
コード例 #48
0
        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);
        }
コード例 #49
0
 public EdmMetadataRepository(InternalContext usersContext, string connectionString, DbProviderFactory providerFactory)
     : base(usersContext, connectionString, providerFactory)
 {
     _existingTransaction = usersContext.TryGetCurrentStoreTransaction();
 }
コード例 #50
0
 // <summary>
 // Initializes a new instance of the <see cref="InternalSqlNonSetQuery" /> class.
 // </summary>
 // <param name="internalContext"> The internal context. </param>
 // <param name="elementType"> Type of the element. </param>
 // <param name="sql"> The SQL. </param>
 // <param name="parameters"> The parameters. </param>
 internal InternalSqlNonSetQuery(InternalContext internalContext, Type elementType, string sql, object[] parameters) : this(internalContext, elementType, sql, /*streaming:*/ null, parameters) {}
コード例 #51
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="DbContextConfiguration" /> class.
        /// </summary>
        /// <param name="internalContext"> The internal context. </param>
        internal DbContextConfiguration(InternalContext internalContext)
        {
            DebugCheck.NotNull(internalContext);

            _internalContext = internalContext;
        }
コード例 #52
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="DbContextConfiguration" /> class.
        /// </summary>
        /// <param name="internalContext"> The internal context. </param>
        internal DbContextConfiguration(InternalContext internalContext)
        {
            Contract.Requires(internalContext != null);

            _internalContext = internalContext;
        }
コード例 #53
0
 public virtual IEnumerable<EntitySet> GetModelTables(InternalContext internalContext)
 {
     return internalContext.ObjectContext.MetadataWorkspace
         .GetItemCollection(DataSpace.SSpace)
         .GetItems<EntityContainer>()
         .Single()
         .BaseEntitySets
         .OfType<EntitySet>()
         .Where(
             s => !s.MetadataProperties.Contains("Type")
                  || (string)s.MetadataProperties["Type"].Value == "Tables");
 }
コード例 #54
0
        public HistoryRepository(
            InternalContext usersContext,
            string connectionString,
            DbProviderFactory providerFactory,
            string contextKey,
            int? commandTimeout,
            Func<DbConnection, string, HistoryContext> historyContextFactory,
            IEnumerable<string> schemas = null,
            DbContext contextForInterception = null,
            DatabaseExistenceState initialExistence = DatabaseExistenceState.Unknown)
            : base(usersContext, connectionString, providerFactory)
        {
            DebugCheck.NotEmpty(contextKey);
            DebugCheck.NotNull(historyContextFactory);

            _initialExistence = initialExistence;
            _commandTimeout = commandTimeout;
            _existingTransaction = usersContext.TryGetCurrentStoreTransaction();

            _schemas
                = new[] { EdmModelExtensions.DefaultSchema }
                    .Concat(schemas ?? Enumerable.Empty<string>())
                    .Distinct();

            _contextForInterception = contextForInterception;
            _historyContextFactory = historyContextFactory;
            DbConnection connection = null;
            try
            {
                connection = CreateConnection();

                using (var context = CreateContext(connection))
                {
                    var historyRowEntity
                        = ((IObjectContextAdapter)context).ObjectContext
                            .MetadataWorkspace
                            .GetItems<EntityType>(DataSpace.CSpace)
                            .Single(et => et.GetClrType() == typeof(HistoryRow));

                    var maxLength
                        = historyRowEntity
                            .Properties
                            .Single(p => p.GetClrPropertyInfo().IsSameAs(MigrationIdProperty))
                            .MaxLength;

                    _migrationIdMaxLength
                        = maxLength.HasValue
                            ? maxLength.Value
                            : HistoryContext.MigrationIdMaxLength;

                    maxLength
                        = historyRowEntity
                            .Properties
                            .Single(p => p.GetClrPropertyInfo().IsSameAs(ContextKeyProperty))
                            .MaxLength;

                    _contextKeyMaxLength
                        = maxLength.HasValue
                            ? maxLength.Value
                            : HistoryContext.ContextKeyMaxLength;
                }
            }
            finally
            {
                DisposeConnection(connection);
            }

            _contextKey = contextKey.RestrictTo(_contextKeyMaxLength);
        }
コード例 #55
0
 internal FakeContext(DbConnection connection, InternalContext internalContext)
     : base(connection, contextOwnsConnection: false)
 {
     _internalContext = internalContext;
 }
コード例 #56
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="DbUpdateConcurrencyException" /> class.
 /// </summary>
 /// <param name="context"> The context. </param>
 /// <param name="innerException"> The inner exception. </param>
 internal DbUpdateConcurrencyException(InternalContext context, OptimisticConcurrencyException innerException)
     : base(context, innerException, involvesIndependentAssociations: false)
 {
 }
コード例 #57
0
        /// <summary>
        ///     Validates that the given name is a property of the declaring type (either on the CLR type or in the EDM)
        ///     and that it is a complex or scalar property rather than a nav property and then returns metadata about
        ///     the property.
        /// </summary>
        /// <param name = "internalContext">The internal context.</param>
        /// <param name = "declaringType">The type that the property is declared on.</param>
        /// <param name = "requestedType">The type of property requested, which may be 'object' if any type can be accepted.</param>
        /// <param name = "propertyName">Name of the property.</param>
        /// <returns>Metadata about the property, or null if the property does not exist or is a navigation property.</returns>
        public static PropertyEntryMetadata ValidateNameAndGetMetadata(
            InternalContext internalContext, Type declaringType, Type requestedType, string propertyName)
        {
            //Contract.Requires(internalContext != null);
            //Contract.Requires(declaringType != null);
            //Contract.Requires(requestedType != null);
            //Contract.Requires(!string.IsNullOrWhiteSpace(propertyName));

            Type propertyType;
            DbHelpers.GetPropertyTypes(declaringType).TryGetValue(propertyName, out propertyType);

            var metadataWorkspace = internalContext.ObjectContext.MetadataWorkspace;
            var edmType = metadataWorkspace.GetItem<StructuralType>(declaringType.FullName, DataSpace.OSpace);

            var isMapped = false;
            var isComplex = false;

            EdmMember member;
            edmType.Members.TryGetValue(propertyName, false, out member);
            if (member != null)
            {
                // If the property is in the model, then it must be a scalar or complex property, not a nav prop
                var edmProperty = member as EdmProperty;
                if (edmProperty == null)
                {
                    return null;
                }

                if (propertyType == null)
                {
                    var asPrimitive = edmProperty.TypeUsage.EdmType as PrimitiveType;
                    if (asPrimitive != null)
                    {
                        propertyType = asPrimitive.ClrEquivalentType;
                    }
                    else
                    {
                        Contract.Assert(
                            edmProperty.TypeUsage.EdmType is StructuralType,
                            "Expected a structural type if property type is not primitive.");

                        var objectItemCollection =
                            (ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace);
                        propertyType = objectItemCollection.GetClrType((StructuralType)edmProperty.TypeUsage.EdmType);
                    }
                }

                isMapped = true;
                isComplex = edmProperty.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType;
            }
            else
            {
                // If the prop is not in the model, then it must have a getter or a setter
                var propertyGetters = DbHelpers.GetPropertyGetters(declaringType);
                var propertySetters = DbHelpers.GetPropertySetters(declaringType);
                if (!(propertyGetters.ContainsKey(propertyName) || propertySetters.ContainsKey(propertyName)))
                {
                    return null;
                }

                Contract.Assert(
                    propertyType != null, "If the property has a getter or setter, then it must exist and have a type.");
            }

            if (!requestedType.IsAssignableFrom(propertyType))
            {
                throw Error.DbEntityEntry_WrongGenericForProp(
                    propertyName, declaringType.Name, requestedType.Name, propertyType.Name);
            }

            return new PropertyEntryMetadata(declaringType, propertyType, propertyName, isMapped, isComplex);
        }