Code:
/ 4.0 / 4.0 / untmp / DEVDIV_TFS / Dev10 / Releases / RTMRel / ndp / fx / src / DataEntity / System / Data / Objects / ObjectContext.cs / 1305376 / ObjectContext.cs
//---------------------------------------------------------------------- //// Copyright (c) Microsoft Corporation. All rights reserved. // // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data.Common; using System.Data.EntityClient; using System.Data.Metadata.Edm; using System.Data.Common.CommandTrees; using System.Data.Common.CommandTrees.Internal; using System.Data.Common.EntitySql; using System.Data.Objects.DataClasses; using System.Data.Objects.Internal; using System.Diagnostics; using System.Text; using System.Transactions; using System.Data.Common.Utils; using System.Globalization; using System.Data.Mapping; using System.Linq; using System.Data.Objects.ELinq; using System.Linq.Expressions; using System.Reflection; using System.Data.Query.InternalTrees; using System.Data.Query.ResultAssembly; using System.Data.Common.Internal.Materialization; using System.Data.Common.CommandTrees.ExpressionBuilder; using System.Runtime.Versioning; using System.Diagnostics.CodeAnalysis; using System.Data.Entity; using System.ComponentModel; namespace System.Data.Objects { ////// Defines options that affect the behavior of the ObjectContext. /// public sealed class ObjectContextOptions { private bool _lazyLoadingEnabled; private bool _proxyCreationEnabled = true; private bool _useLegacyPreserveChangesBehavior = false; internal ObjectContextOptions() { } ////// Get or set boolean that determines if related ends can be loaded on demand /// when they are accessed through a navigation property. /// ////// True if related ends can be loaded on demand; otherwise false. /// public bool LazyLoadingEnabled { get { return _lazyLoadingEnabled; } set { _lazyLoadingEnabled = value; } } ////// Get or set boolean that determines whether proxy instances will be create /// for CLR types with a corresponding proxy type. /// ////// True if proxy instances should be created; otherwise false to create "normal" instances of the type. /// public bool ProxyCreationEnabled { get { return _proxyCreationEnabled; } set { _proxyCreationEnabled = value; } } ////// Get or set a booleanthat determines whether to use the legacy MergeOption.PreserveChanges behavior /// when querying for entities using MergeOption.PreserveChanges /// ////// True if the legacy MergeOption.PreserveChanges behavior should be used; otherwise false. /// public bool UseLegacyPreserveChangesBehavior { get { return _useLegacyPreserveChangesBehavior; } set { _useLegacyPreserveChangesBehavior = value; } } } ////// ObjectContext is the top-level object that encapsulates a connection between the CLR and the database, /// serving as a gateway for Create, Read, Update, and Delete operations. /// public class ObjectContext : IDisposable { #region Fields private IEntityAdapter _adapter; // Connection may be null if used by ObjectMaterializer for detached ObjectContext, // but those code paths should not touch the connection. // // If the connection is null, this indicates that this object has been disposed. // Disposal for this class doesn't mean complete disposal, // but rather the disposal of the underlying connection object if the ObjectContext owns the connection, // or the separation of the underlying connection object from the ObjectContext if the ObjectContext does not own the connection. // // Operations that require a connection should throw an ObjectDiposedException if the connection is null. // Other operations that do not need a connection should continue to work after disposal. private EntityConnection _connection; private readonly MetadataWorkspace _workspace; private ObjectStateManager _cache; private ClrPerspective _perspective; private readonly bool _createdConnection; private bool _openedConnection; // whether or not the context opened the connection to do an operation private int _connectionRequestCount; // the number of active requests for an open connection private int? _queryTimeout; private Transaction _lastTransaction; private static int _objectTypeCount; // Bid counter internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref _objectTypeCount); private bool _disallowSettingDefaultContainerName; private EventHandler _onSavingChanges; private ObjectMaterializedEventHandler _onObjectMaterialized; private ObjectQueryProvider _queryProvider; private readonly ObjectContextOptions _options = new ObjectContextOptions(); private readonly string s_UseLegacyPreserveChangesBehavior = "EntityFramework_UseLegacyPreserveChangesBehavior"; #endregion Fields #region Constructors ////// Creates an ObjectContext with the given connection and metadata workspace. /// /// connection to the store public ObjectContext(EntityConnection connection) : this(EntityUtil.CheckArgumentNull(connection, "connection"), true) { } ////// Creates an ObjectContext with the given connection string and /// default entity container name. This constructor /// creates and initializes an EntityConnection so that the context is /// ready to use; no other initialization is necessary. The given /// connection string must be valid for an EntityConnection; connection /// strings for other connection types are not supported. /// /// the connection string to use in the underlying EntityConnection to the store ///connectionString is null ///if connectionString is invalid [ResourceExposure(ResourceScope.Machine)] //Exposes the file names as part of ConnectionString which are a Machine resource [ResourceConsumption(ResourceScope.Machine)] //For CreateEntityConnection method. But the paths are not created in this method. public ObjectContext(string connectionString) : this(CreateEntityConnection(connectionString), false) { _createdConnection = true; } ////// Creates an ObjectContext with the given connection string and /// default entity container name. This protected constructor creates and initializes an EntityConnection so that the context /// is ready to use; no other initialization is necessary. The given connection string must be valid for an EntityConnection; /// connection strings for other connection types are not supported. /// /// the connection string to use in the underlying EntityConnection to the store /// the name of the default entity container ///connectionString is null ///either connectionString or defaultContainerName is invalid [ResourceExposure(ResourceScope.Machine)] //Exposes the file names as part of ConnectionString which are a Machine resource [ResourceConsumption(ResourceScope.Machine)] //For ObjectContext method. But the paths are not created in this method. protected ObjectContext(string connectionString, string defaultContainerName) : this(connectionString) { DefaultContainerName = defaultContainerName; if (!string.IsNullOrEmpty(defaultContainerName)) { _disallowSettingDefaultContainerName = true; } } ////// Creates an ObjectContext with the given connection and metadata workspace. /// /// connection to the store /// the name of the default entity container protected ObjectContext(EntityConnection connection, string defaultContainerName) : this(connection) { DefaultContainerName = defaultContainerName; if (!string.IsNullOrEmpty(defaultContainerName)) { _disallowSettingDefaultContainerName = true; } } private ObjectContext(EntityConnection connection, bool isConnectionConstructor) { Debug.Assert(null != connection, "null connection"); _connection = connection; _connection.StateChange += ConnectionStateChange; // Ensure a valid connection string connectionString = connection.ConnectionString; if (connectionString == null || connectionString.Trim().Length == 0) { throw EntityUtil.InvalidConnection(isConnectionConstructor, null); } try { _workspace = RetrieveMetadataWorkspaceFromConnection(); } catch (InvalidOperationException e) { // Intercept exceptions retrieving workspace, and wrap exception in appropriate // message based on which constructor pattern is being used. throw EntityUtil.InvalidConnection(isConnectionConstructor, e); } // Register the O and OC metadata if (null != _workspace) { // register the O-Loader if (!_workspace.IsItemCollectionAlreadyRegistered(DataSpace.OSpace)) { ObjectItemCollection itemCollection = new ObjectItemCollection(); _workspace.RegisterItemCollection(itemCollection); } // have the OC-Loader registered by asking for it _workspace.GetItemCollection(DataSpace.OCSpace); } // load config file properties string value = ConfigurationManager.AppSettings[s_UseLegacyPreserveChangesBehavior]; bool useV35Behavior = false; if (Boolean.TryParse(value, out useV35Behavior)) { ContextOptions.UseLegacyPreserveChangesBehavior = useV35Behavior; } } #endregion //Constructors #region Properties ////// Gets the connection to the store. /// ///If the public DbConnection Connection { get { if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } return _connection; } } ///instance has been disposed. /// Gets or sets the default container name. /// public string DefaultContainerName { get { EntityContainer container = Perspective.GetDefaultContainer(); return ((null != container) ? container.Name : String.Empty); } set { if (!_disallowSettingDefaultContainerName) { Perspective.SetDefaultContainer(value); } else { throw EntityUtil.CannotSetDefaultContainerName(); } } } ////// Gets the metadata workspace associated with this ObjectContext. /// [CLSCompliant(false)] public MetadataWorkspace MetadataWorkspace { get { return _workspace; } } ////// Gets the ObjectStateManager used by this ObjectContext. /// public ObjectStateManager ObjectStateManager { get { if (_cache == null) { _cache = new ObjectStateManager(_workspace); } return _cache; } } ////// ClrPerspective based on the MetadataWorkspace. /// internal ClrPerspective Perspective { get { if (_perspective == null) { _perspective = new ClrPerspective(_workspace); } return _perspective; } } ////// Gets and sets the timeout value used for queries with this ObjectContext. /// A null value indicates that the default value of the underlying provider /// will be used. /// public int? CommandTimeout { get { return _queryTimeout; } set { if (value.HasValue && value < 0) { throw EntityUtil.InvalidCommandTimeout("value"); } _queryTimeout = value; } } ////// Gets the LINQ query provider associated with this object context. /// internal protected IQueryProvider QueryProvider { get { if (null == _queryProvider) { _queryProvider = new ObjectQueryProvider(this); } return _queryProvider; } } ////// Whether or not we are in the middle of materialization /// Used to suppress operations such as lazy loading that are not allowed during materialization /// internal bool InMaterialization { get; set; } ////// Get ///instance that contains options /// that affect the behavior of the ObjectContext. /// /// Instance of public ObjectContextOptions ContextOptions { get { return _options; } } #endregion //Properties #region Events ///for the current ObjectContext. /// This value will never be null. /// /// Property for adding a delegate to the SavingChanges Event. /// public event EventHandler SavingChanges { add { _onSavingChanges += value; } remove { _onSavingChanges -= value; } } ////// A private helper function for the _savingChanges/SavingChanges event. /// private void OnSavingChanges() { if (null != _onSavingChanges) { EntityBid.Trace("\n"); _onSavingChanges(this, new EventArgs()); } } /// /// Event raised when a new entity object is materialized. That is, the event is raised when /// a new entity object is created from data in the store as part of a query or load operation. /// ////// Note that the event is raised after included (spanned) referenced objects are loaded, but /// before included (spanned) collections are loaded. Also, for independent associations, /// any stub entities for related objects that have not been loaded will also be created before /// the event is raised. /// /// It is possible for an entity object to be created and then thrown away if it is determined /// that an entity with the same ID already exists in the Context. This event is not raised /// in those cases. /// public event ObjectMaterializedEventHandler ObjectMaterialized { add { _onObjectMaterialized += value; } remove { _onObjectMaterialized -= value; } } internal void OnObjectMaterialized(object entity) { if (null != _onObjectMaterialized) { EntityBid.Trace("\n"); _onObjectMaterialized(this, new ObjectMaterializedEventArgs(entity)); } } /// /// Returns true if any handlers for the ObjectMaterialized event exist. This is /// used for perf reasons to avoid collecting the information needed for the event /// if there is no point in firing it. /// internal bool OnMaterializedHasHandlers { get { return _onObjectMaterialized != null && _onObjectMaterialized.GetInvocationList().Length != 0; } } #endregion //Events #region Methods ////// AcceptChanges on all associated entries in the ObjectStateManager so their resultant state is either unchanged or detached. /// ///public void AcceptAllChanges() { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); if (ObjectStateManager.SomeEntryWithConceptualNullExists()) { throw new InvalidOperationException(Strings.ObjectContext_CommitWithConceptualNull); } // There are scenarios in which order of calling AcceptChanges does matter: // in case there is an entity in Deleted state and another entity in Added state with the same ID - // it is necessary to call AcceptChanges on Deleted entity before calling AcceptChanges on Added entity // (doing this in the other order there is conflict of keys). foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Deleted)) { entry.AcceptChanges(); } foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)) { entry.AcceptChanges(); } ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } private void VerifyRootForAdd(bool doAttach, string entitySetName, IEntityWrapper wrappedEntity, EntityEntry existingEntry, out EntitySet entitySet, out bool isNoOperation) { isNoOperation = false; EntitySet entitySetFromName = null; if (doAttach) { // For AttachTo the entity set name is optional if (!String.IsNullOrEmpty(entitySetName)) { entitySetFromName = this.GetEntitySetFromName(entitySetName); } } else { // For AddObject the entity set name is obligatory entitySetFromName = this.GetEntitySetFromName(entitySetName); } // Find entity set using entity key EntitySet entitySetFromKey = null; EntityKey key = existingEntry != null ? existingEntry.EntityKey : wrappedEntity.GetEntityKeyFromEntity(); if (null != (object)key) { entitySetFromKey = key.GetEntitySet(this.MetadataWorkspace); if (entitySetFromName != null) { // both entity sets are not null, compare them EntityUtil.ValidateEntitySetInKey(key, entitySetFromName, "entitySetName"); } key.ValidateEntityKey(entitySetFromKey); } entitySet = entitySetFromKey ?? entitySetFromName; // Check if entity set was found if (entitySet == null) { throw EntityUtil.EntitySetNameOrEntityKeyRequired(); } this.ValidateEntitySet(entitySet, wrappedEntity.IdentityType); // If in the middle of Attach, try to find the entry by key if (doAttach && existingEntry == null) { // If we don't already have a key, create one now if (null == (object)key) { key = this.ObjectStateManager.CreateEntityKey(entitySet, wrappedEntity.Entity); } existingEntry = this.ObjectStateManager.FindEntityEntry(key); } if (null != existingEntry && !(doAttach && existingEntry.IsKeyEntry)) { if (!Object.ReferenceEquals(existingEntry.Entity, wrappedEntity.Entity)) { throw EntityUtil.ObjectStateManagerContainsThisEntityKey(); } else { EntityState exptectedState = doAttach ? EntityState.Unchanged : EntityState.Added; if (existingEntry.State != exptectedState) { throw doAttach ? EntityUtil.EntityAlreadyExistsInObjectStateManager() : EntityUtil.ObjectStateManagerDoesnotAllowToReAddUnchangedOrModifiedOrDeletedEntity(existingEntry.State); } else { // AttachTo: // Attach is no-op when the existing entry is not a KeyEntry // and it's entity is the same entity instance and it's state is Unchanged // AddObject: // AddObject is no-op when the existing entry's entity is the same entity // instance and it's state is Added isNoOperation = true; return; } } } } /// /// Adds an object to the cache. If it doesn't already have an entity key, the /// entity set is determined based on the type and the O-C map. /// If the object supports relationships (i.e. it implements IEntityWithRelationships), /// this also sets the context onto its RelationshipManager object. /// /// entitySetName the Object to be added. It might be qualifed with container name /// Object to be added. public void AddObject(string entitySetName, object entity) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); EntityBid.Trace("\n"); EntityUtil.CheckArgumentNull(entity, "entity"); EntityEntry existingEntry; IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContextGettingEntry(entity, this, out existingEntry); if (existingEntry == null) { // If the exact object being added is already in the context, there there is no way we need to // load the type for it, and since this is expensive, we only do the load if we have to. // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedEntity.IdentityType, null); } else { Debug.Assert((object)existingEntry.Entity == (object)entity, "FindEntityEntry should return null if existing entry contains a different object."); } EntitySet entitySet; bool isNoOperation; this.VerifyRootForAdd(false, entitySetName, wrappedEntity, existingEntry, out entitySet, out isNoOperation); if (isNoOperation) { return; } System.Data.Objects.Internal.TransactionManager transManager = ObjectStateManager.TransactionManager; transManager.BeginAddTracking(); try { RelationshipManager relationshipManager = wrappedEntity.RelationshipManager; Debug.Assert(relationshipManager != null, "Entity wrapper returned a null RelationshipManager"); bool doCleanup = true; try { // Add the root of the graph to the cache. AddSingleObject(entitySet, wrappedEntity, "entity"); doCleanup = false; } finally { // If we failed after adding the entry but before completely attaching the related ends to the context, we need to do some cleanup. // If the context is null, we didn't even get as far as trying to attach the RelationshipManager, so something failed before the entry // was even added, therefore there is nothing to clean up. if (doCleanup && wrappedEntity.Context == this) { // If the context is not null, it be because the failure happened after it was attached, or it // could mean that this entity was already attached, in which case we don't want to clean it up // If we find the entity in the context and its key is temporary, we must have just added it, so remove it now. EntityEntry entry = this.ObjectStateManager.FindEntityEntry(wrappedEntity.Entity); if (entry != null && entry.EntityKey.IsTemporary) { // devnote: relationshipManager is valid, so entity must be IEntityWithRelationships and casting is safe relationshipManager.NodeVisited = true; // devnote: even though we haven't added the rest of the graph yet, we need to go through the related ends and // clean them up, because some of them could have been attached to the context before the failure occurred RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(wrappedEntity); RelatedEnd.RemoveEntityFromObjectStateManager(wrappedEntity); } // else entry was not added or the key is not temporary, so it must have already been in the cache before we tried to add this product, so don't remove anything } } relationshipManager.AddRelatedEntitiesToObjectStateManager(/*doAttach*/false); } finally { transManager.EndAddTracking(); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } } /// /// Adds an object to the cache without adding its related /// entities. /// /// Object to be added. /// EntitySet name for the Object to be added. It may be qualified with container name /// Container name for the Object to be added. /// Name of the argument passed to a public method, for use in exceptions. internal void AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, string argumentName) { Debug.Assert(entitySet != null, "The extent for an entity must be a non-null entity set."); Debug.Assert(wrappedEntity != null, "The entity wrapper must not be null."); Debug.Assert(wrappedEntity.Entity != null, "The entity must not be null."); EntityKey key = wrappedEntity.GetEntityKeyFromEntity(); if (null != (object)key) { EntityUtil.ValidateEntitySetInKey(key, entitySet); key.ValidateEntityKey(entitySet); } VerifyContextForAddOrAttach(wrappedEntity); wrappedEntity.Context = this; EntityEntry entry = this.ObjectStateManager.AddEntry(wrappedEntity, (EntityKey)null, entitySet, argumentName, true); // If the entity supports relationships, AttachContext on the // RelationshipManager object - with load option of // AppendOnly (if adding a new object to a context, set // the relationships up to cache by default -- load option // is only set to other values when AttachContext is // called by the materializer). Also add all related entitites to // cache. // // NOTE: AttachContext must be called after adding the object to // the cache--otherwise the object might not have a key // when the EntityCollections expect it to. Debug.Assert(this.ObjectStateManager.TransactionManager.TrackProcessedEntities, "Expected tracking processed entities to be true when adding."); Debug.Assert(this.ObjectStateManager.TransactionManager.ProcessedEntities != null, "Expected non-null collection when flag set."); this.ObjectStateManager.TransactionManager.ProcessedEntities.Add(wrappedEntity); wrappedEntity.AttachContext(this, entitySet, MergeOption.AppendOnly); // Find PK values in referenced principals and use these to set FK values entry.FixupFKValuesFromNonAddedReferences(); _cache.FixupReferencesByForeignKeys(entry); wrappedEntity.TakeSnapshotOfRelationships(entry); } ////// Explicitly loads a referenced entity or collection of entities into the given entity. /// ////// After loading, the referenced entity or collection can be accessed through the properties /// of the source entity. /// /// The source entity on which the relationship is defined /// The name of the property to load public void LoadProperty(object entity, string navigationProperty) { IEntityWrapper wrappedEntity = WrapEntityAndCheckContext(entity, "property"); wrappedEntity.RelationshipManager.GetRelatedEnd(navigationProperty).Load(); } ////// Explicitly loads a referenced entity or collection of entities into the given entity. /// ////// After loading, the referenced entity or collection can be accessed through the properties /// of the source entity. /// /// The source entity on which the relationship is defined /// The name of the property to load /// The merge option to use for the load public void LoadProperty(object entity, string navigationProperty, MergeOption mergeOption) { IEntityWrapper wrappedEntity = WrapEntityAndCheckContext(entity, "property"); wrappedEntity.RelationshipManager.GetRelatedEnd(navigationProperty).Load(mergeOption); } ////// Explicitly loads a referenced entity or collection of entities into the given entity. /// ////// After loading, the referenced entity or collection can be accessed through the properties /// of the source entity. /// The property to load is specified by a LINQ expression which must be in the form of /// a simple property member access. For example, /// The source entity on which the relationship is defined /// A LINQ expression specifying the property to load public void LoadProperty(entity) => entity.PropertyName
/// where PropertyName is the navigation property to be loaded. Other expression forms will /// be rejected at runtime. ///(TEntity entity, Expression > selector) { CheckLoadPropertySelectorExpression (selector); IEntityWrapper wrappedEntity = WrapEntityAndCheckContext(entity, "property"); wrappedEntity.RelationshipManager.GetRelatedEnd(((MemberExpression)selector.Body).Member.Name).Load(); } /// /// Explicitly loads a referenced entity or collection of entities into the given entity. /// ////// After loading, the referenced entity or collection can be accessed through the properties /// of the source entity. /// The property to load is specified by a LINQ expression which must be in the form of /// a simple property member access. For example, /// The source entity on which the relationship is defined /// A LINQ expression specifying the property to load /// The merge option to use for the load public void LoadProperty(entity) => entity.PropertyName
/// where PropertyName is the navigation property to be loaded. Other expression forms will /// be rejected at runtime. ///(TEntity entity, Expression > selector, MergeOption mergeOption) { CheckLoadPropertySelectorExpression (selector); IEntityWrapper wrappedEntity = WrapEntityAndCheckContext(entity, "property"); wrappedEntity.RelationshipManager.GetRelatedEnd(((MemberExpression)selector.Body).Member.Name).Load(mergeOption); } // Wraps the given entity and checks that it has a non-null context (i.e. that is is not detached). private IEntityWrapper WrapEntityAndCheckContext(object entity, string refType) { IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContext(entity, this); if (wrappedEntity.Context == null) { throw new InvalidOperationException(System.Data.Entity.Strings.ObjectContext_CannotExplicitlyLoadDetachedRelationships(refType)); } if (wrappedEntity.Context != this) { throw new InvalidOperationException(System.Data.Entity.Strings.ObjectContext_CannotLoadReferencesUsingDifferentContext(refType)); } return wrappedEntity; } // Validates that the given property selector may represent a navigation property. // The actual check that the navigation property is valid is performed by the // RelationshipManager while loading the RelatedEnd. internal static void CheckLoadPropertySelectorExpression (Expression > selector) { EntityUtil.CheckArgumentNull(selector, "selector"); MemberExpression body = selector.Body as MemberExpression; if (body == null || !body.Member.DeclaringType.IsAssignableFrom(typeof(TEntity)) || body.Expression.NodeType != ExpressionType.Parameter) { throw new ArgumentException(System.Data.Entity.Strings.ObjectContext_SelectorExpressionMustBeMemberAccess); } } /// /// Apply modified properties to the original object. /// This API is obsolete. Please use ApplyCurrentValues instead. /// /// name of EntitySet of entity to be updated /// object with modified properties [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] [Obsolete("Use ApplyCurrentValues instead")] public void ApplyPropertyChanges(string entitySetName, object changed) { EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); EntityUtil.CheckArgumentNull(changed, "changed"); this.ApplyCurrentValues(entitySetName, changed); } ////// Apply modified properties to the original object. /// /// name of EntitySet of entity to be updated /// object with modified properties public TEntity ApplyCurrentValues(string entitySetName, TEntity currentEntity) where TEntity : class { EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); EntityUtil.CheckArgumentNull(currentEntity, "currentEntity"); IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContext(currentEntity, this); // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedEntity.IdentityType, null); EntitySet entitySet = this.GetEntitySetFromName(entitySetName); EntityKey key = wrappedEntity.EntityKey; if (null != (object)key) { EntityUtil.ValidateEntitySetInKey(key, entitySet, "entitySetName"); key.ValidateEntityKey(entitySet); } else { key = this.ObjectStateManager.CreateEntityKey(entitySet, currentEntity); } // Check if entity is already in the cache EntityEntry ose = this.ObjectStateManager.FindEntityEntry(key); if (ose == null || ose.IsKeyEntry) { throw EntityUtil.EntityNotTracked(); } ose.ApplyCurrentValuesInternal(wrappedEntity); return (TEntity)ose.Entity; } /// /// Apply original values to the entity. /// The entity to update is found based on key values of the /// name of EntitySet of entity to be updated /// object with original values ///entity and the given . /// updated entity public TEntity ApplyOriginalValues(string entitySetName, TEntity originalEntity) where TEntity : class { EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); EntityUtil.CheckArgumentNull(originalEntity, "originalEntity"); IEntityWrapper wrappedOriginalEntity = EntityWrapperFactory.WrapEntityUsingContext(originalEntity, this); // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedOriginalEntity.IdentityType, null); EntitySet entitySet = this.GetEntitySetFromName(entitySetName); EntityKey key = wrappedOriginalEntity.EntityKey; if (null != (object)key) { EntityUtil.ValidateEntitySetInKey(key, entitySet, "entitySetName"); key.ValidateEntityKey(entitySet); } else { key = this.ObjectStateManager.CreateEntityKey(entitySet, originalEntity); } // Check if the entity is already in the cache EntityEntry ose = this.ObjectStateManager.FindEntityEntry(key); if (ose == null || ose.IsKeyEntry) { throw EntityUtil.EntityNotTrackedOrHasTempKey(); } if (ose.State != EntityState.Modified && ose.State != EntityState.Unchanged && ose.State != EntityState.Deleted) { throw EntityUtil.EntityMustBeUnchangedOrModifiedOrDeleted(ose.State); } if (ose.WrappedEntity.IdentityType != wrappedOriginalEntity.IdentityType) { throw EntityUtil.EntitiesHaveDifferentType(ose.Entity.GetType().FullName, originalEntity.GetType().FullName); } ose.CompareKeyProperties(originalEntity); // The ObjectStateEntry.UpdateModifiedFields uses a variation of Shaper.UpdateRecord method // which additionaly marks properties as modified as necessary. ose.UpdateOriginalValues(wrappedOriginalEntity.Entity); // return the current entity return (TEntity)ose.Entity; } /// /// Attach entity graph into the context in the Unchanged state. /// This version takes entity which doesn't have to have a Key. /// /// EntitySet name for the Object to be attached. It may be qualified with container name /// public void AttachTo(string entitySetName, object entity) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); EntityBid.Trace("\n"); EntityUtil.CheckArgumentNull(entity, "entity"); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); EntityEntry existingEntry; IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContextGettingEntry(entity, this, out existingEntry); if (existingEntry == null) { // If the exact object being added is already in the context, there there is no way we need to // load the type for it, and since this is expensive, we only do the load if we have to. // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedEntity.IdentityType, null); } else { Debug.Assert((object)existingEntry.Entity == (object)entity, "FindEntityEntry should return null if existing entry contains a different object."); } EntitySet entitySet; bool isNoOperation; this.VerifyRootForAdd(true, entitySetName, wrappedEntity, existingEntry, out entitySet, out isNoOperation); if (isNoOperation) { return; } System.Data.Objects.Internal.TransactionManager transManager = ObjectStateManager.TransactionManager; transManager.BeginAttachTracking(); try { this.ObjectStateManager.TransactionManager.OriginalMergeOption = wrappedEntity.MergeOption; RelationshipManager relationshipManager = wrappedEntity.RelationshipManager; Debug.Assert(relationshipManager != null, "Entity wrapper returned a null RelationshipManager"); bool doCleanup = true; try { // Attach the root of entity graph to the cache. AttachSingleObject(wrappedEntity, entitySet, "entity"); doCleanup = false; } finally { // SQLBU 555615 Be sure that wrappedEntity.Context == this to not try to detach // entity from context if it was already attached to some other context. // It's enough to check this only for the root of the graph since we can assume that all entities // in the graph are attached to the same context (or none of them is attached). if (doCleanup && wrappedEntity.Context == this) { // SQLBU 509900 RIConstraints: Entity still exists in cache after Attach fails // // Cleaning up is needed only when root of the graph violates some referential constraint. // Normal cleaning is done in RelationshipManager.AddRelatedEntitiesToObjectStateManager() // (referential constraints properties are checked in AttachSingleObject(), before // AddRelatedEntitiesToObjectStateManager is called, that's why normal cleaning // doesn't work in this case) relationshipManager.NodeVisited = true; // devnote: even though we haven't attached the rest of the graph yet, we need to go through the related ends and // clean them up, because some of them could have been attached to the context. RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(wrappedEntity); RelatedEnd.RemoveEntityFromObjectStateManager(wrappedEntity); } } relationshipManager.AddRelatedEntitiesToObjectStateManager(/*doAttach*/true); } finally { transManager.EndAttachTracking(); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } } /// /// Attach entity graph into the context in the Unchanged state. /// This version takes entity which does have to have a non-temporary Key. /// /// public void Attach(IEntityWithKey entity) { EntityBid.Trace("\n"); EntityUtil.CheckArgumentNull(entity, "entity"); if (null == (object)entity.EntityKey) { throw EntityUtil.CannotAttachEntityWithoutKey(); } this.AttachTo(null, entity); } /// /// Attaches single object to the cache without adding its related entities. /// /// Entity to be attached. /// "Computed" entity set. /// Name of the argument passed to a public method, for use in exceptions. internal void AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet, string argumentName) { Debug.Assert(wrappedEntity != null, "entity wrapper shouldn't be null"); Debug.Assert(wrappedEntity.Entity != null, "entity shouldn't be null"); Debug.Assert(entitySet != null, "entitySet shouldn't be null"); // Try to detect if the entity is invalid as soon as possible // (before adding the entity to the ObjectStateManager) RelationshipManager relationshipManager = wrappedEntity.RelationshipManager; Debug.Assert(relationshipManager != null, "Entity wrapper returned a null RelationshipManager"); EntityKey key = wrappedEntity.GetEntityKeyFromEntity(); if (null != (object)key) { EntityUtil.ValidateEntitySetInKey(key, entitySet); key.ValidateEntityKey(entitySet); } else { key = this.ObjectStateManager.CreateEntityKey(entitySet, wrappedEntity.Entity); } Debug.Assert(key != null, "GetEntityKey should have returned a non-null key"); // Temporary keys are not allowed if (key.IsTemporary) { throw EntityUtil.CannotAttachEntityWithTemporaryKey(); } if (wrappedEntity.EntityKey != key) { wrappedEntity.EntityKey = key; } // Check if entity already exists in the cache. // NOTE: This check could be done earlier, but this way I avoid creating key twice. EntityEntry entry = ObjectStateManager.FindEntityEntry(key); if (null != entry) { if (entry.IsKeyEntry) { // devnote: SQLBU 555615. This method was extracted from PromoteKeyEntry to have consistent // behavior of AttachTo in case of attaching entity which is already attached to some other context. // We can not detect if entity is attached to another context until we call SetChangeTrackerOntoEntity // which throws exception if the change tracker is already set. // SetChangeTrackerOntoEntity is now called from PromoteKeyEntryInitialization(). // Calling PromoteKeyEntryInitialization() before calling relationshipManager.AttachContext prevents // overriding Context property on relationshipManager (and attaching relatedEnds to current context). this.ObjectStateManager.PromoteKeyEntryInitialization(entry, wrappedEntity, /*shadowValues*/ null, /*replacingEntry*/ false); Debug.Assert(this.ObjectStateManager.TransactionManager.TrackProcessedEntities, "Expected tracking processed entities to be true when adding."); Debug.Assert(this.ObjectStateManager.TransactionManager.ProcessedEntities != null, "Expected non-null collection when flag set."); this.ObjectStateManager.TransactionManager.ProcessedEntities.Add(wrappedEntity); wrappedEntity.AttachContext(this, entitySet, MergeOption.AppendOnly); wrappedEntity.TakeSnapshotOfRelationships(entry); this.ObjectStateManager.PromoteKeyEntry(entry, wrappedEntity, /*shadowValues*/ null, /*replacingEntry*/ false, /*setIsLoaded*/ false, /*keyEntryInitialized*/ true, "Attach"); ObjectStateManager.FixupReferencesByForeignKeys(entry); relationshipManager.CheckReferentialConstraintProperties(entry); } else { Debug.Assert(!Object.ReferenceEquals(entry.Entity, wrappedEntity.Entity)); throw EntityUtil.ObjectStateManagerContainsThisEntityKey(); } } else { VerifyContextForAddOrAttach(wrappedEntity); wrappedEntity.Context = this; entry = this.ObjectStateManager.AttachEntry(key, wrappedEntity, entitySet, argumentName); Debug.Assert(this.ObjectStateManager.TransactionManager.TrackProcessedEntities, "Expected tracking processed entities to be true when adding."); Debug.Assert(this.ObjectStateManager.TransactionManager.ProcessedEntities != null, "Expected non-null collection when flag set."); this.ObjectStateManager.TransactionManager.ProcessedEntities.Add(wrappedEntity); wrappedEntity.AttachContext(this, entitySet, MergeOption.AppendOnly); ObjectStateManager.FixupReferencesByForeignKeys(entry); wrappedEntity.TakeSnapshotOfRelationships(entry); relationshipManager.CheckReferentialConstraintProperties(entry); } } ////// When attaching we need to check that the entity is not already attached to a different context /// before we wipe away that context. /// private void VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity) { if (wrappedEntity.Context != null && wrappedEntity.Context != this && !wrappedEntity.Context.ObjectStateManager.IsDisposed && wrappedEntity.MergeOption != MergeOption.NoTracking) { throw EntityUtil.EntityCantHaveMultipleChangeTrackers(); } } ////// Create entity key based on given entity set and values of given entity. /// /// entity set of the entity /// entity ///new instance of entity key public EntityKey CreateEntityKey(string entitySetName, object entity) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); EntityUtil.CheckArgumentNull(entity, "entity"); // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(EntityUtil.GetEntityIdentityType(entity.GetType()), null); EntitySet entitySet = this.GetEntitySetFromName(entitySetName); return this.ObjectStateManager.CreateEntityKey(entitySet, entity); } internal EntitySet GetEntitySetFromName(string entitySetName) { string setName; string containerName; ObjectContext.GetEntitySetName(entitySetName, "entitySetName", this, out setName, out containerName); // Find entity set using entitySetName and entityContainerName return this.GetEntitySet(setName, containerName); } private void AddRefreshKey(object entityLike, Dictionaryentities, Dictionary > currentKeys) { Debug.Assert(!(entityLike is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); if (null == entityLike) { throw EntityUtil.NthElementIsNull(entities.Count); } IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContext(entityLike, this); EntityKey key = wrappedEntity.EntityKey; RefreshCheck(entities, entityLike, key); // Retrieve the EntitySet for the EntityKey and add an entry in the dictionary // that maps a set to the keys of entities that should be refreshed from that set. EntitySet entitySet = key.GetEntitySet(this.MetadataWorkspace); List setKeys = null; if (!currentKeys.TryGetValue(entitySet, out setKeys)) { setKeys = new List (); currentKeys.Add(entitySet, setKeys); } setKeys.Add(key); } /// /// Creates an ObjectSet based on the EntitySet that is defined for TEntity. /// Requires that the DefaultContainerName is set for the context and that there is a /// single EntitySet for the specified type. Throws exception if more than one type is found. /// ///Entity type for the requested ObjectSet public ObjectSetCreateObjectSet () where TEntity : class { EntitySet entitySet = GetEntitySetForType(typeof(TEntity), "TEntity"); return new ObjectSet (entitySet, this); } /// /// Find the EntitySet in the default EntityContainer for the specified CLR type. /// Must be a valid mapped entity type and must be mapped to exactly one EntitySet across all of the EntityContainers in the metadata for this context. /// /// CLR type to use for EntitySet lookup. ///private EntitySet GetEntitySetForType(Type entityCLRType, string exceptionParameterName) { EntitySet entitySetForType = null; EntityContainer defaultContainer = this.Perspective.GetDefaultContainer(); if (defaultContainer == null) { // We don't have a default container, so look through all EntityContainers in metadata to see if // we can find exactly one EntitySet that matches the specified CLR type. System.Collections.ObjectModel.ReadOnlyCollection entityContainers = this.MetadataWorkspace.GetItems (DataSpace.CSpace); foreach (EntityContainer entityContainer in entityContainers) { // See if this container has exactly one EntitySet for this type EntitySet entitySetFromContainer = GetEntitySetFromContainer(entityContainer, entityCLRType, exceptionParameterName); if (entitySetFromContainer != null) { // Verify we haven't already found a matching EntitySet in some other container if (entitySetForType != null) { // There is more than one EntitySet for this type across all containers in metadata, so we can't determine which one the user intended throw EntityUtil.MultipleEntitySetsFoundInAllContainers(entityCLRType.FullName, exceptionParameterName); } entitySetForType = entitySetFromContainer; } } } else { // There is a default container, so restrict the search to EntitySets within it entitySetForType = GetEntitySetFromContainer(defaultContainer, entityCLRType, exceptionParameterName); } // We still may not have found a matching EntitySet for this type if (entitySetForType == null) { throw EntityUtil.NoEntitySetFoundForType(entityCLRType.FullName, exceptionParameterName); } return entitySetForType; } private EntitySet GetEntitySetFromContainer(EntityContainer container, Type entityCLRType, string exceptionParameterName) { // Verify that we have an EdmType mapping for the specified CLR type EdmType entityEdmType = GetTypeUsage(entityCLRType).EdmType; // Try to find a single EntitySet for the specified type EntitySet entitySet = null; foreach (EntitySetBase es in container.BaseEntitySets) { // This is a match if the set is an EntitySet (not an AssociationSet) and the EntitySet // is defined for the specified entity type. Must be an exact match, not a base type. if (es.BuiltInTypeKind == BuiltInTypeKind.EntitySet && es.ElementType == entityEdmType) { if (entitySet != null) { // There is more than one EntitySet for this type, so we can't determine which one the user intended throw EntityUtil.MultipleEntitySetsFoundInSingleContainer(entityCLRType.FullName, container.Name, exceptionParameterName); } entitySet = (EntitySet)es; } } return entitySet; } /// /// Creates an ObjectSet based on the specified EntitySet name. /// ///Expected type of the EntitySet /// /// EntitySet to use for the ObjectSet. Can be fully-qualified or unqualified if the DefaultContainerName is set. /// public ObjectSetCreateObjectSet (string entitySetName) where TEntity : class { EntitySet entitySet = GetEntitySetForNameAndType(entitySetName, typeof(TEntity), "TEntity"); return new ObjectSet (entitySet, this); } /// /// Finds an EntitySet with the specified name and verifies that its type matches the specified type. /// /// /// Name of the EntitySet to find. Can be fully-qualified or unqualified if the DefaultContainerName is set /// /// /// Expected CLR type of the EntitySet. Must exactly match the type for the EntitySet, base types are not valid. /// /// Argument name to use if an exception occurs. ///EntitySet that was found in metadata with the specified parameters private EntitySet GetEntitySetForNameAndType(string entitySetName, Type entityCLRType, string exceptionParameterName) { // Verify that the specified entitySetName exists in metadata EntitySet entitySet = GetEntitySetFromName(entitySetName); // Verify that the EntitySet type matches the specified type exactly (a base type is not valid) EdmType entityEdmType = GetTypeUsage(entityCLRType).EdmType; if (entitySet.ElementType != entityEdmType) { throw EntityUtil.InvalidEntityTypeForObjectSet(entityCLRType.FullName, entitySet.ElementType.FullName, entitySetName, exceptionParameterName); } return entitySet; } #region Connection Management ////// Ensures that the connection is opened for an operation that requires an open connection to the store. /// Calls to EnsureConnection MUST be matched with a single call to ReleaseConnection. /// ///If the internal void EnsureConnection() { if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } if (ConnectionState.Closed == Connection.State) { Connection.Open(); _openedConnection = true; } if (_openedConnection) { _connectionRequestCount++; } // Check the connection was opened correctly if ((_connection.State == ConnectionState.Closed) || (_connection.State == ConnectionState.Broken)) { string message = System.Data.Entity.Strings.EntityClient_ExecutingOnClosedConnection( _connection.State == ConnectionState.Closed ? System.Data.Entity.Strings.EntityClient_ConnectionStateClosed : System.Data.Entity.Strings.EntityClient_ConnectionStateBroken); throw EntityUtil.InvalidOperation(message); } try { // Make sure the necessary metadata is registered EnsureMetadata(); #region EnsureContextIsEnlistedInCurrentTransaction // The following conditions are no longer valid since Metadata Independence. Debug.Assert(ConnectionState.Open == _connection.State, "Connection must be open."); // TABLE OF ACTIONS WE PERFORM HERE: // // lastTransaction currentTransaction ConnectionState WillClose Action // null null Open No no-op; // non-null tx1 non-null tx1 Open No no-op; // null non-null Closed Yes connection.Open(); // null non-null Open No connection.Enlist(currentTransaction); // non-null null Open No connection.Enlist(currentTransaction); // non-null null Closed Yes no-op; // non-null tx1 non-null tx2 Open No connection.Enlist(currentTransaction); // non-null tx1 non-null tx2 Open Yes connection.Close(); connection.Open(); // non-null tx1 non-null tx2 Closed Yes connection.Open(); // Transaction currentTransaction = Transaction.Current; bool transactionHasChanged = (null != currentTransaction && !currentTransaction.Equals(_lastTransaction)) || (null != _lastTransaction && !_lastTransaction.Equals(currentTransaction)); if (transactionHasChanged) { if (!_openedConnection || (null == _lastTransaction && _connectionRequestCount > 1)) { // We didn't open the connection, or we're enlisting for the first time, // so we have to (or can in the latter case) just enlist the connection // in the transaction. _connection.EnlistTransaction(currentTransaction); } else if (_connectionRequestCount > 1) // only if we didn't open the connection this time (multiple active requests) { // We'll close and reopen the connection to get the benefit of automatic // transaction enlistment, if we didn't just open the connection _connection.Close(); _connection.Open(); _openedConnection = true; _connectionRequestCount++; } } else { // we don't need to do anything, nothing has changed. } // If we get here, we have an open connection, either enlisted in the current // transaction (if it's non-null) or unenlisted from all transactions (if the // current transaction is null) _lastTransaction = currentTransaction; #endregion } catch (Exception) { // when the connection is unable to enlist properly or another error occured, be sure to release this connection ReleaseConnection(); throw; } } ///instance has been disposed. /// Resets the state of connection management when the connection becomes closed. /// /// /// private void ConnectionStateChange(object sender, StateChangeEventArgs e) { if (e.CurrentState == ConnectionState.Closed) { _connectionRequestCount = 0; _openedConnection = false; } } ////// Releases the connection, potentially closing the connection if no active operations /// require the connection to be open. There should be a single ReleaseConnection call /// for each EnsureConnection call. /// ///If the internal void ReleaseConnection() { if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } if (_openedConnection) { Debug.Assert(_connectionRequestCount > 0, "_connectionRequestCount is zero or negative"); if (_connectionRequestCount > 0) { _connectionRequestCount--; } // When no operation is using the connection and the context had opened the connection // the connection can be closed if (_connectionRequestCount == 0) { Connection.Close(); _openedConnection = false; } } } internal void EnsureMetadata() { if (!MetadataWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.SSpace)) { Debug.Assert(!MetadataWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.CSSpace), "ObjectContext has C-S metadata but not S?"); // Only throw an ObjectDisposedException if an attempt is made to access the underlying connection object. if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } MetadataWorkspace connectionWorkspace = _connection.GetMetadataWorkspace(); Debug.Assert(connectionWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.CSpace) && connectionWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.SSpace) && connectionWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.CSSpace), "EntityConnection.GetMetadataWorkspace() did not return an initialized workspace?"); // Validate that the context's MetadataWorkspace and the underlying connection's MetadataWorkspace // have the same CSpace collection. Otherwise, an error will occur when trying to set the SSpace // and CSSpace metadata ItemCollection connectionCSpaceCollection = connectionWorkspace.GetItemCollection(DataSpace.CSpace); ItemCollection contextCSpaceCollection = MetadataWorkspace.GetItemCollection(DataSpace.CSpace); if (!object.ReferenceEquals(connectionCSpaceCollection, contextCSpaceCollection)) { throw EntityUtil.ContextMetadataHasChanged(); } MetadataWorkspace.RegisterItemCollection(connectionWorkspace.GetItemCollection(DataSpace.SSpace)); MetadataWorkspace.RegisterItemCollection(connectionWorkspace.GetItemCollection(DataSpace.CSSpace)); } } #endregion #if OBJECTLAYERENTITYSQLPARSER ///instance has been disposed. /// Returns an EntitySqlParser object configured to work with this connection. /// ///public EntitySqlParser GetEntitySqlParser() { EnsureMetadata(); return new EntitySqlParser(this.Perspective); } #endif //OBJECTLAYERENTITYSQLPARSER /// /// Creates an ObjectQuery ///over the store, ready to be executed. /// type of the query result /// the query string to be executed /// parameters to pass to the query ///an ObjectQuery instance, ready to be executed public ObjectQueryCreateQuery (string queryString, params ObjectParameter[] parameters) { EntityUtil.CheckArgumentNull(queryString, "queryString"); EntityUtil.CheckArgumentNull(parameters, "parameters"); // SQLBUDT 447285: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We either auto-load 's assembly into the ObjectItemCollection or we auto-load the user's calling assembly and its referenced assemblies. // If the entities in the user's result spans multiple assemblies, the user must manually call LoadFromAssembly. // *GetCallingAssembly returns the assembly of the method that invoked the currently executing method. MetadataWorkspace.ImplicitLoadAssemblyForType(typeof(T), System.Reflection.Assembly.GetCallingAssembly()); // create a ObjectQuery with default settings ObjectQuery query = new ObjectQuery (queryString, this, MergeOption.AppendOnly); foreach (ObjectParameter parameter in parameters) { query.Parameters.Add(parameter); } return query; } /// /// Creates an EntityConnection from the given connection string. /// /// the connection string ///the newly created connection [ResourceExposure(ResourceScope.Machine)] //Exposes the file names as part of ConnectionString which are a Machine resource [ResourceConsumption(ResourceScope.Machine)] //For EntityConnection constructor. But the paths are not created in this method. private static EntityConnection CreateEntityConnection(string connectionString) { EntityUtil.CheckStringArgument(connectionString, "connectionString"); // create the connection EntityConnection connection = new EntityConnection(connectionString); return connection; } ////// Given an entity connection, returns a copy of its MetadataWorkspace. Ensure we get /// all of the metadata item collections by priming the entity connection. /// ////// If the private MetadataWorkspace RetrieveMetadataWorkspaceFromConnection() { if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } MetadataWorkspace connectionWorkspace = _connection.GetMetadataWorkspace(false /* initializeAllConnections */); Debug.Assert(connectionWorkspace != null, "EntityConnection.MetadataWorkspace is null."); // Create our own workspace MetadataWorkspace workspace = connectionWorkspace.ShallowCopy(); return workspace; } ///instance has been disposed. /// Marks an object for deletion from the cache. /// /// Object to be deleted. public void DeleteObject(object entity) { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); // This method and ObjectSet.DeleteObject are expected to have identical behavior except for the extra validation ObjectSet // requests by passing a non-null expectedEntitySetName. Any changes to this method are expected to be made in the common // internal overload below that ObjectSet also uses, unless there is a specific reason why a behavior is desired when the // call comes from ObjectContext only. EntityBid.Trace("\n"); DeleteObject(entity, null /*expectedEntitySetName*/); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } /// /// Common DeleteObject method that is used by both ObjectContext.DeleteObject and ObjectSet.DeleteObject. /// /// Object to be deleted. /// /// EntitySet that the specified object is expected to be in. Null if the caller doesn't want to validate against a particular EntitySet. /// internal void DeleteObject(object entity, EntitySet expectedEntitySet) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); EntityUtil.CheckArgumentNull(entity, "entity"); EntityEntry cacheEntry = this.ObjectStateManager.FindEntityEntry(entity); if (cacheEntry == null || !object.ReferenceEquals(cacheEntry.Entity, entity)) { throw EntityUtil.CannotDeleteEntityNotInObjectStateManager(); } if (expectedEntitySet != null) { EntitySetBase actualEntitySet = cacheEntry.EntitySet; if (actualEntitySet != expectedEntitySet) { throw EntityUtil.EntityNotInObjectSet_Delete(actualEntitySet.EntityContainer.Name, actualEntitySet.Name, expectedEntitySet.EntityContainer.Name, expectedEntitySet.Name); } } cacheEntry.Delete(); // Detaching from the context happens when the object // actually detaches from the cache (not just when it is // marked for deletion). } ////// Detach entity from the cache. /// /// Object to be detached. public void Detach(object entity) { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); // This method and ObjectSet.DetachObject are expected to have identical behavior except for the extra validation ObjectSet // requests by passing a non-null expectedEntitySetName. Any changes to this method are expected to be made in the common // internal overload below that ObjectSet also uses, unless there is a specific reason why a behavior is desired when the // call comes from ObjectContext only. EntityBid.Trace("\n"); Detach(entity, null /*expectedEntitySet*/); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } /// /// Common Detach method that is used by both ObjectContext.Detach and ObjectSet.Detach. /// /// Object to be detached. /// /// EntitySet that the specified object is expected to be in. Null if the caller doesn't want to validate against a particular EntitySet. /// internal void Detach(object entity, EntitySet expectedEntitySet) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); EntityUtil.CheckArgumentNull(entity, "entity"); EntityEntry cacheEntry = this.ObjectStateManager.FindEntityEntry(entity); if (cacheEntry == null || !object.ReferenceEquals(cacheEntry.Entity, entity) || cacheEntry.Entity == null) // this condition includes key entries and relationship entries { throw EntityUtil.CannotDetachEntityNotInObjectStateManager(); } if (expectedEntitySet != null) { EntitySetBase actualEntitySet = cacheEntry.EntitySet; if (actualEntitySet != expectedEntitySet) { throw EntityUtil.EntityNotInObjectSet_Detach(actualEntitySet.EntityContainer.Name, actualEntitySet.Name, expectedEntitySet.EntityContainer.Name, expectedEntitySet.Name); } } cacheEntry.Detach(); } ////// Disposes this ObjectContext. /// public void Dispose() { // Technically, calling GC.SuppressFinalize is not required because the class does not // have a finalizer, but it does no harm, protects against the case where a finalizer is added // in the future, and prevents an FxCop warning. GC.SuppressFinalize(this); EntityBid.Trace("\n"); Dispose(true); } /// /// Disposes this ObjectContext. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) { if (disposing) { // Release managed resources here. // Dispose the connection the ObjectContext created if (_createdConnection && _connection != null) { _connection.Dispose(); } _connection = null; // Marks this object as disposed. _adapter = null; if (_cache != null) { _cache.Dispose(); } } // Release unmanaged resources here (none for this class). } #region GetEntitySet ////// Returns the EntitySet with the given name from given container. /// /// name of entity set /// name of container ///the appropriate EntitySet ///the entity set could not be found for the given name ///the entity container could not be found for the given name internal EntitySet GetEntitySet(string entitySetName, string entityContainerName) { Debug.Assert(entitySetName != null, "entitySetName should be not null"); EntityContainer container = null; if (String.IsNullOrEmpty(entityContainerName)) { container = this.Perspective.GetDefaultContainer(); Debug.Assert(container != null, "Problem with metadata - default container not found"); } else { if (!this.MetadataWorkspace.TryGetEntityContainer(entityContainerName, DataSpace.CSpace, out container)) { throw EntityUtil.EntityContainterNotFoundForName(entityContainerName); } } EntitySet entitySet = null; if (!container.TryGetEntitySetByName(entitySetName, false, out entitySet)) { throw EntityUtil.EntitySetNotFoundForName(TypeHelpers.GetFullName(container.Name, entitySetName)); } return entitySet; } private static void GetEntitySetName(string qualifiedName, string parameterName, ObjectContext context, out string entityset, out string container) { entityset = null; container = null; EntityUtil.CheckStringArgument(qualifiedName, parameterName); string[] result = qualifiedName.Split('.'); if (result.Length > 2) { throw EntityUtil.QualfiedEntitySetName(parameterName); } if (result.Length == 1) // if not . at all { entityset = result[0]; } else { container = result[0]; entityset = result[1]; if (container == null || container.Length == 0) // if it start with . { throw EntityUtil.QualfiedEntitySetName(parameterName); } } if (entityset == null || entityset.Length == 0) // if it does not have ES name : containrname. { throw EntityUtil.QualfiedEntitySetName(parameterName); } if (context != null && String.IsNullOrEmpty(container) && (context.Perspective.GetDefaultContainer() == null)) { throw EntityUtil.ContainerQualifiedEntitySetNameRequired(parameterName); } } ////// Validate that an EntitySet is compatible with a given entity instance's CLR type. /// /// an EntitySet /// The CLR type of an entity instance private void ValidateEntitySet(EntitySet entitySet, Type entityType) { TypeUsage entityTypeUsage = GetTypeUsage(entityType); if (!entitySet.ElementType.IsAssignableFrom(entityTypeUsage.EdmType)) { throw EntityUtil.InvalidEntitySetOnEntity(entitySet.Name, entityType, "entity"); } } internal TypeUsage GetTypeUsage(Type entityCLRType) { // Register the assembly so the type information will be sure to be loaded in metadata this.MetadataWorkspace.ImplicitLoadAssemblyForType(entityCLRType, System.Reflection.Assembly.GetCallingAssembly()); TypeUsage entityTypeUsage = null; if (!this.Perspective.TryGetType(entityCLRType, out entityTypeUsage) || !TypeSemantics.IsEntityType(entityTypeUsage)) { throw EntityUtil.InvalidEntityType(entityCLRType); } Debug.Assert(entityTypeUsage != null, "entityTypeUsage is null"); return entityTypeUsage; } #endregion ////// Retrieves an object from the cache if present or from the /// store if not. /// /// Key of the object to be found. ///Entity object. public object GetObjectByKey(EntityKey key) { EntityUtil.CheckArgumentNull(key, "key"); EntitySet entitySet = key.GetEntitySet(this.MetadataWorkspace); Debug.Assert(entitySet != null, "Key's EntitySet should not be null in the MetadataWorkspace"); // SQLBUDT 447285: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // Either the entity type's assembly is already in the ObjectItemCollection or we auto-load the user's calling assembly and its referenced assemblies. // *GetCallingAssembly returns the assembly of the method that invoked the currently executing method. MetadataWorkspace.ImplicitLoadFromEntityType(entitySet.ElementType, System.Reflection.Assembly.GetCallingAssembly()); object entity; if (!TryGetObjectByKey(key, out entity)) { throw EntityUtil.ObjectNotFound(); } return entity; } #region Refresh ////// Refreshing cache data with store data for specific entities. /// The order in which entites are refreshed is non-deterministic. /// /// Determines how the entity retrieved from the store is merged with the entity in the cache /// must not be null and all entities must be attached to this context. May be empty. ///if refreshMode is not valid ///collection is null ///collection contains null or non entities or entities not attached to this context public void Refresh(RefreshMode refreshMode, IEnumerable collection) { IntPtr hscp; EntityBid.ScopeEnter(out hscp, "refreshMode=%d{RefreshMode}, collection", (int)refreshMode); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); try { EntityUtil.CheckArgumentRefreshMode(refreshMode); EntityUtil.CheckArgumentNull(collection, "collection"); // collection may not contain any entities -- this is valid for this overload RefreshEntities(refreshMode, collection); } finally { EntityBid.ScopeLeave(ref hscp); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } } /// /// Refreshing cache data with store data for a specific entity. /// /// Determines how the entity retrieved from the store is merged with the entity in the cache /// The entity to refresh. This must be a non-null entity that is attached to this context ///if refreshMode is not valid ///entity is null ///entity is not attached to this context public void Refresh(RefreshMode refreshMode, object entity) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); IntPtr hscp; EntityBid.ScopeEnter(out hscp, "refreshMode=%d{RefreshMode}, entity, collection", (int)refreshMode); try { EntityUtil.CheckArgumentRefreshMode(refreshMode); EntityUtil.CheckArgumentNull(entity, "entity"); RefreshEntities(refreshMode, new object[] { entity }); } finally { EntityBid.ScopeLeave(ref hscp); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } } /// /// Validates that the given entity/key pair has an ObjectStateEntry /// and that entry is not in the added state. /// /// The entity is added to the entities dictionary, and checked for duplicates. /// /// on exit, entity is added to this dictionary. /// An object reference that is not "Added," has an ObjectStateEntry and is not in the entities list. /// private void RefreshCheck( Dictionaryentities, object entity, EntityKey key) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); Debug.Assert(entity != null, "The entity is null."); EntityEntry entry = ObjectStateManager.FindEntityEntry(key); if (null == entry) { throw EntityUtil.NthElementNotInObjectStateManager(entities.Count); } if (EntityState.Added == entry.State) { throw EntityUtil.NthElementInAddedState(entities.Count); } Debug.Assert(EntityState.Added != entry.State, "not expecting added"); Debug.Assert(EntityState.Detached != entry.State, "not expecting detached"); try { entities.Add(key, entry); // don't ignore duplicates } catch (ArgumentException e) { EntityUtil.TraceExceptionForCapture(e); throw EntityUtil.NthElementIsDuplicate(entities.Count); } Debug.Assert(null != entity, "null entity"); Debug.Assert(null != (object)key, "null entity.Key"); Debug.Assert(null != key.EntitySetName, "null entity.Key.EntitySetName"); } private void RefreshEntities(RefreshMode refreshMode, IEnumerable collection) { // refreshMode and collection should already be validated prior to this call -- collection can be empty in one Refresh overload // but not in the other, so we need to do that check before we get to this common method Debug.Assert(collection != null, "collection may not contain any entities but should never be null"); bool openedConnection = false; try { Dictionary entities = new Dictionary (RefreshEntitiesSize(collection)); #region 1) Validate and bucket the entities by entity set Dictionary > refreshKeys = new Dictionary >(); foreach (object entity in collection) // anything other than object risks InvalidCastException { AddRefreshKey(entity, entities, refreshKeys); } // The collection is no longer required at this point. collection = null; #endregion #region 2) build and execute the query for each set of entities EntityBid.Trace(" minimumExecutions=%d, plannedRefreshCount=%d\n", refreshKeys.Count, entities.Count); if (refreshKeys.Count > 0) { EnsureConnection(); openedConnection = true; // All entities from a single set can potentially be refreshed in the same query. // However, the refresh operations are batched in an attempt to avoid the generation // of query trees or provider SQL that exhaust available client or server resources. foreach (EntitySet targetSet in refreshKeys.Keys) { List setKeys = refreshKeys[targetSet]; int refreshedCount = 0; while (refreshedCount < setKeys.Count) { refreshedCount = BatchRefreshEntitiesByKey(refreshMode, entities, targetSet, setKeys, refreshedCount); } } } // The refreshKeys list is no longer required at this point. refreshKeys = null; #endregion #region 3) process the unrefreshed entities EntityBid.Trace(" unrefreshedCount=%d\n", entities.Count); if (RefreshMode.StoreWins == refreshMode) { // remove all entites that have been removed from the store, not added by client foreach (KeyValuePair item in entities) { Debug.Assert(EntityState.Added != item.Value.State, "should not be possible"); if (EntityState.Detached != item.Value.State) { // We set the detaching flag here even though we are deleting because we are doing a // Delete/AcceptChanges cycle to simulate a Detach, but we can't use Detach directly // because legacy behavior around cascade deletes should be preserved. However, we // do want to prevent FK values in dependents from being nulled, which is why we // need to set the detaching flag. ObjectStateManager.TransactionManager.BeginDetaching(); try { item.Value.Delete(); } finally { ObjectStateManager.TransactionManager.EndDetaching(); } Debug.Assert(EntityState.Detached != item.Value.State, "not expecting detached"); item.Value.AcceptChanges(); } } } else if ((RefreshMode.ClientWins == refreshMode) && (0 < entities.Count)) { // throw an exception with all appropriate entity keys in text string prefix = String.Empty; StringBuilder builder = new StringBuilder(); foreach (KeyValuePair item in entities) { Debug.Assert(EntityState.Added != item.Value.State, "should not be possible"); if (item.Value.State == EntityState.Deleted) { // Detach the deleted items because this is the client changes and the server // does not have these items any more item.Value.AcceptChanges(); } else { builder.Append(prefix).Append(Environment.NewLine); builder.Append('\'').Append(item.Key.ConcatKeyValue()).Append('\''); prefix = ","; } } // If there were items that could not be found, throw an exception if (builder.Length > 0) { throw EntityUtil.ClientEntityRemovedFromStore(builder.ToString()); } } #endregion } finally { if (openedConnection) { ReleaseConnection(); } } } private int BatchRefreshEntitiesByKey(RefreshMode refreshMode, Dictionary trackedEntities, EntitySet targetSet, List targetKeys, int startFrom) { // // A single refresh query can be built for all entities from the same set. // For each entity set, a DbFilterExpression is constructed that // expresses the equivalent of: // // SELECT VALUE e // FROM AS e // WHERE // GetRefKey(GetEntityRef(e)) == .KeyValues // [OR GetRefKey(GetEntityRef(e)) == .KeyValues // [..OR GetRefKey(GetEntityRef(e)) == .KeyValues]] // // Note that a LambdaFunctionExpression is used so that instead // of repeating GetRefKey(GetEntityRef(e)) a VariableReferenceExpression // to a Lambda argument with the value GetRefKey(GetEntityRef(e)) is used instead. // The query is therefore logically equivalent to: // // SELECT VALUE e // FROM AS e // WHERE // LET(x = GetRefKey(GetEntityRef(e)) IN ( // x == .KeyValues // [OR x == .KeyValues // [..OR x == .KeyValues]] // ) // // The batch size determines the maximum depth of the predicate OR tree and // also limits the size of the generated provider SQL that is sent to the server. const int maxBatch = 250; // Bind the target EntitySet under the name "EntitySet". DbExpressionBinding entitySetBinding = targetSet.Scan().BindAs("EntitySet"); // Use the variable from the set binding as the 'e' in a new GetRefKey(GetEntityRef(e)) expression. DbExpression sourceEntityKey = entitySetBinding.Variable.GetEntityRef().GetRefKey(); // Build the where predicate as described above. A maximum of entity keys will be included // in the predicate, starting from position in the list of entity keys. As each key is // included, both and are incremented to ensure that the batch size is // correctly constrained and that the new starting position for the next call to this method is calculated. int batchSize = Math.Min(maxBatch, (targetKeys.Count - startFrom)); DbExpression[] keyFilters = new DbExpression[batchSize]; for (int idx = 0; idx < batchSize; idx++) { // Create a row constructor expression based on the key values of the EntityKey. KeyValuePair [] keyValueColumns = targetKeys[startFrom++].GetKeyValueExpressions(targetSet); DbExpression keyFilter = DbExpressionBuilder.NewRow(keyValueColumns); // Create an equality comparison between the row constructor and the lambda variable // that refers to GetRefKey(GetEntityRef(e)), which also produces a row // containing key values, but for the current entity from the entity set. keyFilters[idx] = sourceEntityKey.Equal(keyFilter); } // Sanity check that the batch includes at least one element. Debug.Assert(batchSize > 0, "Didn't create a refresh expression?"); // Build a balanced binary tree that OR's the key filters together. DbExpression entitySetFilter = Helpers.BuildBalancedTreeInPlace(keyFilters, DbExpressionBuilder.Or); // Create a FilterExpression based on the EntitySet binding and the Lambda predicate. // This FilterExpression encapsulated the logic required for the refresh query as described above. DbExpression refreshQuery = entitySetBinding.Filter(entitySetFilter); // Initialize the command tree used to issue the refresh query. DbQueryCommandTree tree = DbQueryCommandTree.FromValidExpression(this.MetadataWorkspace, DataSpace.CSpace, refreshQuery); // Evaluate the refresh query using ObjectQuery and process the results to update the ObjectStateManager. MergeOption mergeOption = (RefreshMode.StoreWins == refreshMode ? MergeOption.OverwriteChanges : MergeOption.PreserveChanges); // The connection will be released by ObjectResult when enumeration is complete. this.EnsureConnection(); try { ObjectResult
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- DataGridViewImageColumn.cs
- CompositeCollection.cs
- StreamInfo.cs
- TimeSpanConverter.cs
- TextSelection.cs
- ResourceAttributes.cs
- _SpnDictionary.cs
- DataGridComponentEditor.cs
- ReflectionTypeLoadException.cs
- Stroke2.cs
- ToolboxComponentsCreatingEventArgs.cs
- updatecommandorderer.cs
- SortKey.cs
- RequestCacheManager.cs
- FixedTextBuilder.cs
- TrackPoint.cs
- TreeViewDesigner.cs
- HwndHost.cs
- TextDecorationCollection.cs
- LinqDataSourceSelectEventArgs.cs
- SystemInfo.cs
- RemoveStoryboard.cs
- CopyAttributesAction.cs
- ImageSource.cs
- ToolConsole.cs
- TransformProviderWrapper.cs
- ObjectQueryState.cs
- GradientSpreadMethodValidation.cs
- HandlerMappingMemo.cs
- KnownBoxes.cs
- FormsAuthenticationModule.cs
- EmptyElement.cs
- ToolStripProgressBar.cs
- HostProtectionPermission.cs
- CodeAttributeDeclarationCollection.cs
- AttachedPropertyMethodSelector.cs
- ActivityCodeDomSerializer.cs
- MarkupCompilePass1.cs
- TypeUtil.cs
- HtmlDocument.cs
- DependencyPropertyValueSerializer.cs
- ProcessHostMapPath.cs
- ReceiveDesigner.xaml.cs
- TypeLibConverter.cs
- InternalDispatchObject.cs
- DataGridViewAdvancedBorderStyle.cs
- SQLDecimal.cs
- TextLineResult.cs
- Baml2006ReaderSettings.cs
- PerformanceCounterPermissionEntryCollection.cs
- WebPartRestoreVerb.cs
- BinaryMessageFormatter.cs
- DynamicPropertyHolder.cs
- HexParser.cs
- SEHException.cs
- WebPartVerb.cs
- ManualResetEventSlim.cs
- Visual.cs
- FilterEventArgs.cs
- IssuedTokensHeader.cs
- ResolveDuplexAsyncResult.cs
- TableLayout.cs
- ThicknessConverter.cs
- ButtonChrome.cs
- Binding.cs
- SynchronousChannel.cs
- RMEnrollmentPage2.cs
- EventSinkHelperWriter.cs
- PipeSecurity.cs
- OleCmdHelper.cs
- UriTemplateLiteralQueryValue.cs
- TypeConverterValueSerializer.cs
- FixedSOMImage.cs
- WeakReferenceEnumerator.cs
- WebBrowserUriTypeConverter.cs
- GacUtil.cs
- DateTimeValueSerializer.cs
- ResourceAttributes.cs
- ElementHost.cs
- TripleDESCryptoServiceProvider.cs
- DateTimeConstantAttribute.cs
- EntityException.cs
- InkCanvasAutomationPeer.cs
- RankException.cs
- UseLicense.cs
- DataBinding.cs
- DetailsViewPageEventArgs.cs
- XsltQilFactory.cs
- ToolStripProfessionalLowResolutionRenderer.cs
- ArrayConverter.cs
- AdapterDictionary.cs
- SizeFConverter.cs
- Vector.cs
- UnionCqlBlock.cs
- OracleDateTime.cs
- XmlSchemaCollection.cs
- SectionUpdates.cs
- UnrecognizedAssertionsBindingElement.cs
- SspiHelper.cs
- AtomParser.cs