ObjectContext.cs source code in C# .NET

Source code for the .NET framework in C#

                        

Code:

/ Net / Net / 3.5.50727.3053 / DEVDIV / depot / DevDiv / releases / Orcas / SP / ndp / fx / src / DataEntity / System / Data / Objects / ObjectContext.cs / 4 / ObjectContext.cs

                            //---------------------------------------------------------------------- 
// 
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// 
// 
// @owner       [....]
// @backupOwner [....] 
//--------------------------------------------------------------------- 

using System; 
using System.Collections;
using System.Collections.Generic;
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.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; 

namespace System.Data.Objects 
{ 
    /// 
    /// 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 = null; 
 
        private ObjectQueryProvider _queryProvider;
        #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 
        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
        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);
            }
        } 

        #endregion //Constructors 
 
        #region Properties
        ///  
        /// Gets the connection to the store.
        /// 
        /// If the  instance has been disposed.
        public DbConnection Connection 
        {
            get 
            { 
                if (_connection == null)
                { 
                    throw EntityUtil.ObjectContextDisposed();
                }

                return _connection; 
            }
        } 
 
        /// 
        /// 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.
        ///  
        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 IQueryProvider Provider 
        { 
            get
            { 
                if (null == _queryProvider)
                {
                    _queryProvider = new ObjectQueryProvider(this);
                } 
                return _queryProvider;
            } 
        } 

        #endregion //Properties 

        #region Events
        /// 
        /// 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());
            }
        }
        #endregion //Events 

        #region Methods 
        ///  
        /// AcceptChanges on all associated entries in the ObjectStateManager so their resultant state is either unchanged or detached.
        ///  
        /// 
        public void AcceptAllChanges()
        {
            // 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(); 
            } 
        }
 
        /// 
        /// 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) 
        {
            EntityBid.Trace("\n");
            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.LoadAssemblyForType(entity.GetType(), null); 

            EntitySet entitySet = this.GetEntitySetFromName(entitySetName);

            RelationshipManager relationshipManager = EntityUtil.GetRelationshipManager(entity); 
            bool doCleanup = true;
            try 
            { 
                // Add the root of the graph to the cache.
                AddSingleObject(entitySet, entity, "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 && relationshipManager != null && relationshipManager.Context != null)
                { 
                    // 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.
                    ObjectStateEntry entry = this.ObjectStateManager.FindObjectStateEntry(entity); 
                    if (entry != null && entry.EntityKey.IsTemporary)
                    { 
                        // devnote: relationshipManager is valid, so entity must be IEntityWithRelationships and casting is safe 
                        relationshipManager.NodeVisited = true;
                        IEntityWithRelationships entityWithRelationships = (IEntityWithRelationships)entity; 
                        // 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
                        HashSet promotedEntityKeyRefs = new HashSet(); // no key refs could have been promoted yet
                        RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(entityWithRelationships, promotedEntityKeyRefs); 
                        Debug.Assert(promotedEntityKeyRefs.Count == 0, "Haven't cleaned up all of the promoted reference EntityKeys");
                        RelatedEnd.RemoveEntityFromObjectStateManager(entityWithRelationships); 
                    } 
                    // 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
                } 
            }

            if (relationshipManager != null)
            { 
                relationshipManager.AddRelatedEntitiesToObjectStateManager(/*doAttach*/false);
            } 
        } 
        /// 
        /// 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, object entity, string argumentName) 
        {
            Debug.Assert(entitySet != null, "The extent for an entity must be a non-null entity set."); 
            Debug.Assert(entity != null, "The entity must not be null.");

            // Try to detect if the entity is invalid as soon as possible
            // (before adding the entity to the ObjectStateManager) 
            RelationshipManager relationshipManager = EntityUtil.GetRelationshipManager(entity);
 
            EntityKey key = ObjectContext.FindEntityKey(entity, this); 
            if (null != (object)key)
            { 
                EntityUtil.ValidateEntitySetInKey(key, entitySet);
                key.ValidateEntityKey(entitySet);
            }
 
            this.ObjectStateManager.AddEntry(entity, (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.
            if (relationshipManager != null) 
            {
                relationshipManager.AttachContext(this, entitySet, MergeOption.AppendOnly);
            }
        } 

        ///  
        /// Apply modified properties to the original object. 
        /// 
        /// name of EntitySet of entity to be updated 
        /// object with modified properties
        public void ApplyPropertyChanges(string entitySetName, object changed)
        {
            EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); 
            EntityUtil.CheckArgumentNull(changed, "changed");
 
            // 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.LoadAssemblyForType(changed.GetType(), null);

            EntitySet entitySet = this.GetEntitySetFromName(entitySetName); 

            EntityKey key = ObjectContext.FindEntityKey(changed, this); 
            if (null != (object)key) 
            {
                EntityUtil.ValidateEntitySetInKey(key, entitySet, "entitySetName"); 
                key.ValidateEntityKey(entitySet);
            }
            else
            { 
                key = this.CreateEntityKey(entitySet, changed);
            } 
 
            // Check if entity is already in the cache
            ObjectStateEntry ose = this.ObjectStateManager.FindObjectStateEntry(key); 
            if (ose == null || ose.IsKeyEntry)
            {
                throw EntityUtil.NoEntryExistsForObject(changed);
            } 

            if (ose.State != EntityState.Modified && 
                ose.State != EntityState.Unchanged) 
            {
                throw EntityUtil.EntityMustBeUnchangedOrModified(ose.State); 
            }

            if (ose.Entity.GetType() != changed.GetType())
            { 
                throw EntityUtil.EntitiesHaveDifferentType(ose.Entity.GetType().FullName, changed.GetType().FullName);
            } 
 
            ose.CompareKeyProperties(changed);
 
            Shaper.UpdateRecord(changed, ose.CurrentValues);
        }

 
        /// 
        /// 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)
        {
            EntityBid.Trace("\n"); 
            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.LoadAssemblyForType(entity.GetType(), null);

            // Find entity set using given entity set name 
            EntitySet entitySetFromName = null;
            if (!String.IsNullOrEmpty(entitySetName)) 
            { 
                entitySetFromName = this.GetEntitySetFromName(entitySetName);
            } 

            // Find entity set using entity key
            EntitySet entitySetFromKey = null;
            EntityKey key = ObjectContext.FindEntityKey(entity, this); 
            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 entitySet = entitySetFromKey ?? entitySetFromName;
 
            // Check if entity set was found
            if (entitySet == null)
            {
                throw EntityUtil.EntitySetNameOrEntityKeyRequired(); 
            }
 
            this.ValidateEntitySet(entitySet, entity.GetType()); 

            // Check if entity is already in the cache 
            ObjectStateEntry existingEntry = this.ObjectStateManager.FindObjectStateEntry(key);
            if (null != existingEntry && !existingEntry.IsKeyEntry)
            {
                if (!Object.ReferenceEquals(existingEntry.Entity, entity)) 
                {
                    throw EntityUtil.ObjectStateManagerContainsThisEntityKey(); 
                } 
                else
                { 
                    if (existingEntry.State != EntityState.Unchanged)
                    {
                        throw EntityUtil.EntityAlreadyExistsInObjectStateManager();
                    } 
                    else
                    { 
                        // 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
                        return; 
                    }
                }
            }
 
            this.ObjectStateManager.BeginAttachTracking();
 
            try 
            {
                RelationshipManager relationshipManager = EntityUtil.GetRelationshipManager(entity); 
                bool doCleanup = true;
                try
                {
                    // Attach the root of entity graph to the cache. 
                    AttachSingleObject(entity, entitySet, "entity");
                    doCleanup = false; 
                } 
                finally
                { 
                    // SQLBU 555615 Be sure that relationshipManager.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 && relationshipManager != null && relationshipManager.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) 

                        // devnote: relationshipManager is valid, so entity must be IEntityWithRelationships and casting is safe 
                        relationshipManager.NodeVisited = true; 
                        IEntityWithRelationships entityWithRelationships = (IEntityWithRelationships)entity;
                        // 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.
                        HashSet promotedEntityKeyRefs = new HashSet(); // no key refs could have been promoted yet
                        RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(entityWithRelationships, promotedEntityKeyRefs);
                        Debug.Assert(promotedEntityKeyRefs.Count == 0, "Haven't cleaned up all of the promoted reference EntityKeys"); 
                        RelatedEnd.RemoveEntityFromObjectStateManager(entityWithRelationships);
                    } 
                } 

                if (relationshipManager != null) 
                {
                    relationshipManager.AddRelatedEntitiesToObjectStateManager(/*doAttach*/true);
                }
            } 
            finally
            { 
                this.ObjectStateManager.EndAttachTracking(); 
            }
        } 
        /// 
        /// 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(object entity, EntitySet entitySet, string argumentName) 
        { 
            Debug.Assert(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 = EntityUtil.GetRelationshipManager(entity); 

            EntityKey key = ObjectContext.FindEntityKey(entity, this); 
            if (null != (object)key) 
            {
                EntityUtil.ValidateEntitySetInKey(key, entitySet); 
                key.ValidateEntityKey(entitySet);
            }
            else
            { 
                key = this.CreateEntityKey(entitySet, entity);
            } 
 
            Debug.Assert(key != null, "GetEntityKey should have returned a non-null key");
 
            // Temporary keys are not allowed
            if (key.IsTemporary)
            {
                throw EntityUtil.CannotAttachEntityWithTemporaryKey(); 
            }
 
            IEntityWithKey entityWithKey = entity as IEntityWithKey; 
            if (null != (object)entityWithKey && null == (object)entityWithKey.EntityKey)
            { 
                EntityUtil.SetKeyOntoEntity(entity, key);
            }

            // Check if entity already exists in the cache. 
            // NOTE: This check could be done earlier, but this way I avoid creating key twice.
            ObjectStateEntry existingEntry = ObjectStateManager.FindObjectStateEntry(key); 
 
            if (null != existingEntry)
            { 
                if (existingEntry.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(existingEntry, entity, /*shadowValues*/ null, /*replacingEntry*/ false);

                    if (relationshipManager != null)
                    { 
                        relationshipManager.AttachContext(this, entitySet, MergeOption.AppendOnly);
                    } 
                    this.ObjectStateManager.PromoteKeyEntry(existingEntry, entity, /*shadowValues*/ null, /*replacingEntry*/ false, /*setIsLoaded*/ false, /*keyEntryInitialized*/ true, "Attach"); 
                    if (relationshipManager != null)
                    { 
                        relationshipManager.CheckReferentialConstraintProperties(key);
                    }
                }
                else 
                {
                    Debug.Assert(!Object.ReferenceEquals(existingEntry.Entity, entity)); 
                    throw EntityUtil.ObjectStateManagerContainsThisEntityKey(); 
                }
            } 
            else
            {
                this.ObjectStateManager.AttachEntry(key, entity, entitySet, argumentName);
                if (relationshipManager != null) 
                {
                    relationshipManager.AttachContext(this, entitySet, MergeOption.AppendOnly); 
                    relationshipManager.CheckReferentialConstraintProperties(key); 
                }
            } 
        }

        /// 
        /// 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) 
        {
            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.LoadAssemblyForType(entity.GetType(), null); 

            EntitySet entitySet = this.GetEntitySetFromName(entitySetName);

            return this.CreateEntityKey(entitySet, entity); 
        }
 
        internal EntityKey CreateEntityKey(EntitySet entitySet, object entity) 
        {
            Debug.Assert(entitySet != null, "null entitySet"); 
            Debug.Assert(entity != null, "null entity");

            // Creates an EntityKey based on the values in the entity and the given EntitySet
            ReadOnlyMetadataCollection keyMembers = entitySet.ElementType.KeyMembers; 
            StateManagerTypeMetadata typeMetadata = ObjectStateManager.GetOrAddStateManagerTypeMetadata(entity.GetType(), entitySet);
            object[] keyValues = new object[keyMembers.Count]; 
 
            for (int i = 0; i < keyMembers.Count; ++i)
            { 
                string keyName = keyMembers[i].Name;
                int ordinal = typeMetadata.GetOrdinalforCLayerMemberName(keyName);
                if (ordinal < 0)
                { 
                    throw EntityUtil.EntityTypeDoesNotMatchEntitySet(entity.GetType().FullName, entitySet.Name, "entity");
                } 
 
                keyValues[i] = typeMetadata.Member(ordinal).GetValue(entity);
            } 

            if (keyValues.Length == 1)
            {
                return new EntityKey(entitySet, keyValues[0]); 
            }
            else 
            { 
                return new EntityKey(entitySet, keyValues);
            } 
        }

        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, Dictionary entities, Dictionary> currentKeys)
        { 
            if (null == entityLike) 
            {
                throw EntityUtil.NthElementIsNull(entities.Count); 
            }

            EntityKey key = ObjectContext.FindEntityKey(entityLike, this);
            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);
        } 

        #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  instance has been disposed.
        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; 
            }

        }
 
        /// 
        /// 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  instance has been disposed. 
        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

 
        /// 
        /// 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 ObjectQuery CreateQuery(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.LoadAssemblyForType(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
        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  instance has been disposed.
        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; 
        }
        ///  
        /// Marks an object for deletion from the cache. 
        /// 
        /// Object to be deleted. 
        public void DeleteObject(object entity)
        {
            EntityBid.Trace("\n");
            EntityUtil.CheckArgumentNull(entity, "entity"); 

            ObjectStateEntry cacheEntry = this.ObjectStateManager.FindObjectStateEntry(entity); 
            if (cacheEntry == null || !object.ReferenceEquals(cacheEntry.Entity, entity)) 
            {
                throw EntityUtil.CannotDeleteEntityNotInObjectStateManager(); 
            }

            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) 
        {
            EntityBid.Trace("\n"); 
            EntityUtil.CheckArgumentNull(entity, "entity"); 

            ObjectStateEntry cacheEntry = this.ObjectStateManager.FindObjectStateEntry(entity); 
            if (cacheEntry == null ||
                !object.ReferenceEquals(cacheEntry.Entity, entity) ||
                cacheEntry.Entity == null) // this condition includes key entries and relationship entries
            { 
                throw EntityUtil.CannotDetachEntityNotInObjectStateManager();
            } 
 
            cacheEntry.Detach();
        } 

        /// 
        /// Disposes this ObjectContext.
        ///  
        public void Dispose()
        { 
            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;
            }
            // 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 = null; 
            if (!this.Perspective.TryGetType(entityType, out entityTypeUsage) || 
                !TypeSemantics.IsEntityType(entityTypeUsage))
            { 
                throw EntityUtil.InvalidEntityType("entity", entityType);
            }
            if (!entitySet.ElementType.IsAssignableFrom(entityTypeUsage.EdmType))
            { 
                throw EntityUtil.InvalidEntitySetOnEntity(entitySet.Name, entityType, "entity");
            } 
        } 
        #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.LoadFromEntityType(entitySet.ElementType, System.Reflection.Assembly.GetCallingAssembly()); 

            object entity;
            if (!TryGetObjectByKey(key, out entity))
            { 
                throw EntityUtil.ObjectNotFound();
            } 
            return entity; 
        }
 
        /// 
        /// Returns the key on an entity.
        /// Used in circumstances in which the context.ObjectStateManager might be null.
        ///  
        /// 
        ///  
        static internal EntityKey FindEntityKey(object entity, ObjectContext context) 
        {
            IEntityWithKey entityWithKey = entity as IEntityWithKey; 
            if (null != entityWithKey)
            {
                return entityWithKey.EntityKey;
            } 
            if (null != context._cache)
            { 
                EntityKey key; 
                if (context.ObjectStateManager.TryGetEntityKey(entity, out key))
                { 
                    return key;
                }
            }
            return null; 
        }
 
        #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);
            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); 
            }
        } 
        ///  
        /// 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) 
        { 
            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);
            }
        }
 
        private void RefreshCheck(
            Dictionary entities, 
            object entity, EntityKey key) 
        {
            Debug.Assert(entity != null, "The entity is null."); 

            ObjectStateEntry entry = ObjectStateManager.FindObjectStateEntry(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) 
                        {
                            item.Value.Delete(); 
                            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;

            // Initialize the command tree used to build the refresh query.
            DbQueryCommandTree tree = new DbQueryCommandTree(this.MetadataWorkspace, DataSpace.CSpace); 

            // Bind the target EntitySet under the name "EntitySet". 
            DbExpressionBinding entitySetBinding = tree.CreateExpressionBinding(tree.CreateScanExpression(targetSet), "EntitySet"); 

            // Use the variable from the set binding as the 'e' in a new GetRefKey(GetEntityRef(e)) expression. 
            DbExpression boundEntityKey = tree.CreateRefKeyExpression(tree.CreateEntityRefExpression(entitySetBinding.Variable));

            // Create a new VariableReference expression with which to refer to the key values
            // of the current entity from within the 'where' predicate of the refresh query. 
            // This will later be bound to GetRefKey(GetEntityRef(e)) by an enclosing LambdaFunction.
            DbVariableReferenceExpression sourceEntityKeyVarRef = tree.CreateVariableReferenceExpression("EntityKey", boundEntityKey.ResultType); 
 
            // 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(tree, targetSet);
                DbExpression keyFilter = tree.CreateNewRowExpression(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] = tree.CreateEqualsExpression(sourceEntityKeyVarRef, 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, tree.CreateOrExpression);
 
            //
            // Create a new LambdaFunctionExpression that binds GetRefKey(GetEntityRef("EntitySet")) 
            // to the bound entity key variable name, "EntityKey" and uses the predicate expression 
            // build above as its Lambda body expression.
            // This correctly binds the variable used in the predicate. 
            //
            KeyValuePair[] lambdaFormals = new KeyValuePair[1];
            lambdaFormals[0] = new KeyValuePair(sourceEntityKeyVarRef.VariableName, sourceEntityKeyVarRef.ResultType);
 
            DbExpression[] lambdaArgs = new DbExpression[1];
            lambdaArgs[0] = boundEntityKey; 
 
            entitySetFilter = tree.CreateLambdaFunctionExpression(lambdaFormals, entitySetFilter, lambdaArgs);
 
            // 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.
            tree.Query = tree.CreateFilterExpression(entitySetBinding, entitySetFilter);
 
            // 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 results = ObjectQueryExecutionPlan.ExecuteCommandTree(this, tree, mergeOption); 
 
                foreach (object entity in results)
                { 
                    // There is a risk that, during an event, the Entity removed itself from the cache.
                    ObjectStateEntry entry = ObjectStateManager.FindObjectStateEntry(entity);
                    if ((null != entry) && (EntityState.Modified == entry.State))
                    {   // this is 'ForceChanges' - which is the same as PreserveChanges, except all properties are marked modified. 
                        Debug.Assert(RefreshMode.ClientWins == refreshMode, "StoreWins always becomes unchanged");
                        entry.SetModifiedAll(); 
                    } 

                    EntityKey key = this.ObjectStateManager.GetEntityKey(entity); 
                    bool flag = trackedEntities.Remove(key);
                    Debug.Assert(flag, "Refreshed entity not in collection");
                }
            } 
            catch
            { 
                // Enumeration did not complete, so the connection must be explicitly released. 
                this.ReleaseConnection();
                throw; 
            }

            // Return the position in the list from which the next refresh operation should start.
            // This will be equal to the list count if all remaining entities in the list were 
            // refreshed during this call.
            return startFrom; 
        } 

        private static int RefreshEntitiesSize(IEnumerable collection) 
        {
            ICollection list = collection as ICollection;
            return ((null != list) ? list.Count : 0);
        } 
        #endregion
 
        #region SaveChanges 
        /// 
        /// Persists all updates to the store. 
        /// 
        /// 
        ///   the number of dirty (i.e., Added, Modified, or Deleted) ObjectStateEntries
        ///   in the ObjectStateManager when SaveChanges was called. 
        /// 
        public Int32 SaveChanges() 
        { 
            return SaveChanges(true);
        } 

        /// 
        /// Persists all updates to the store.
        ///  
        /// if false, user must call AcceptAllChanges/>
        ///  
        ///   the number of dirty (i.e., Added, Modified, or Deleted) ObjectStateEntries 
        ///   in the ObjectStateManager when SaveChanges was called.
        ///  
        public Int32 SaveChanges(bool acceptChangesDuringSave)
        {
            OnSavingChanges();
 
            bool mustReleaseConnection = false;
            Int32 entriesAffected = ObjectStateManager.GetObjectStateEntriesCount(EntityState.Added | EntityState.Deleted | EntityState.Modified); 
            using (new EntityBid.ScopeAuto(" %d#, affectingEntries=%d", ObjectID, entriesAffected)) 
            {
                EntityConnection connection = (EntityConnection)Connection; 

                if (0 < entriesAffected)
                {   // else fast exit if no changes to save to avoids interacting with or starting of new transactions
 
                    // get data adapter
                    if (_adapter == null) 
                    { 
                        IServiceProvider sp = connection.ProviderFactory as IServiceProvider;
                        if (sp != null) 
                        {
                            _adapter = sp.GetService(typeof(IEntityAdapter)) as IEntityAdapter;
                        }
                        if (_adapter == null) 
                        {
                            throw EntityUtil.InvalidDataAdapter(); 
                        } 
                    }
                    // only accept changes after the local transaction commits 
                    _adapter.AcceptChangesDuringUpdate = false;
                    _adapter.Connection = connection;
                    _adapter.CommandTimeout = this.CommandTimeout;
 
                    try
                    { 
                        EnsureConnection(); 
                        mustReleaseConnection = true;
 
                        // determine what transaction to enlist in
                        Transaction currentTransaction = Transaction.Current;
                        bool needLocalTransaction = false;
                        if (null == connection.CurrentTransaction) 
                        {
                            // If there isn't a local transaction, we'll attempt to enlist on the 
                            // current SysTx transaction so we don't need to construct a local 
                            // transaction.
 

                            needLocalTransaction = (null == _lastTransaction);
                        }
                        // else user already has their own local transaction going; user will do the abort or commit. 

                        DbTransaction localTransaction = null; 
                        try 
                        {
                            // EntityConnection tracks the CurrentTransaction we don't need to pass it around 
                            if (needLocalTransaction)
                            {
                                localTransaction = connection.BeginTransaction();
                            } 
                            entriesAffected = _adapter.Update(ObjectStateManager);
 
                            if (null != localTransaction) 
                            {   // we started the local transaction; so we also commit it
                                localTransaction.Commit(); 
                            }
                            // else on success with no exception is thrown, user generally commits the transaction
                        }
                        finally 
                        {
                            if (null != localTransaction) 
                            {   // we started the local transaction; so it requires disposal (rollback if not previously committed 
                                localTransaction.Dispose();
                            } 
                            // else on failure with an exception being thrown, user generally aborts (default action with transaction without an explict commit)
                        }
                    }
                    finally 
                    {
                        if (mustReleaseConnection) 
                        { 
                            // Release the connection when we are done with the save
                            ReleaseConnection(); 
                        }
                    }

                    if (acceptChangesDuringSave) 
                    {   // only accept changes after the local transaction commits
 
                        try 
                        {
                            AcceptAllChanges(); 
                        }
                        catch (Exception e)
                        {
                            // If AcceptAllChanges throw - let's inform user that changes in database were committed 
                            // and that Context and Database can be in inconsistent state.
 
                            // We should not be wrapping all exceptions 
                            if (EntityUtil.IsCatchableExceptionType(e))
                            { 
                                throw EntityUtil.AcceptAllChangesFailure(e);
                            }
                            throw;
                        } 
                    }
                } 
            } 
            return entriesAffected;
        } 
        #endregion

        /// 
        /// Attempts to retrieve an object from the cache or the store. 
        /// 
        /// Key of the object to be found. 
        /// Out param for the object. 
        /// True if the object was found, false otherwise.
        public bool TryGetObjectByKey(EntityKey key, out object value) 
        {
            // try the cache first
            ObjectStateEntry entry;
            ObjectStateManager.TryGetObjectStateEntry(key, out entry); // this will check key argument 
            if (entry != null)
            { 
                // can't find keys 
                if (!entry.IsKeyEntry)
                { 
                    // SQLBUDT 511296 returning deleted object.
                    value = entry.Entity;
                    return value != null;
                } 
            }
 
            if (key.IsTemporary) 
            {
                // If the key is temporary, we cannot find a corresponding object in the store. 
                value = null;
                return false;
            }
 
            EntitySet entitySet = key.GetEntitySet(this.MetadataWorkspace);
            Debug.Assert(entitySet != null, "Key's EntitySet should not be null in the MetadataWorkspace"); 
 
            // Validate the EntityKey values against the EntitySet
            key.ValidateEntityKey(entitySet, true /*isArgumentException*/, "key"); 

            // 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.LoadFromEntityType(entitySet.ElementType, System.Reflection.Assembly.GetCallingAssembly()); 
 
            // Execute the query:
            // SELECT VALUE X FROM [EC].[ES] AS X 
            // WHERE X.KeyProp0 = @p0 AND X.KeyProp1 = @p1 AND ...
            // parameters are the key values

            // Build the Entity SQL query 
            StringBuilder esql = new StringBuilder();
            esql.AppendFormat("SELECT VALUE X FROM {0}.{1} AS X WHERE ", QuoteIdentifier(entitySet.EntityContainer.Name), QuoteIdentifier(entitySet.Name)); 
            EntityKeyMember[] members = key.EntityKeyValues; 
            ReadOnlyMetadataCollection keyMembers = entitySet.ElementType.KeyMembers;
            ObjectParameter[] parameters = new ObjectParameter[members.Length]; 

            for(int i =0; i< members.Length; i++)
            {
                if (i > 0) 
                {
                    esql.Append(" AND "); 
                } 
                string parameterName = string.Format(CultureInfo.InvariantCulture, "p{0}", i.ToString(CultureInfo.InvariantCulture));
                esql.AppendFormat("X.{0} = @{1}", QuoteIdentifier(members[i].Key), parameterName); 
                parameters[i] = new ObjectParameter(parameterName, members[i].Value);

                // Try to set the TypeUsage on the ObjectParameter
                EdmMember keyMember = null; 
                if (keyMembers.TryGetValue(members[i].Key, true, out keyMember))
                { 
                    parameters[i].TypeUsage = keyMember.TypeUsage; 
                }
            } 

            // Execute the query
            object entity = null;
            ObjectResult results = CreateQuery(esql.ToString(), parameters).Execute(MergeOption.AppendOnly); 
            foreach (object queriedEntity in results)
            { 
                Debug.Assert(entity == null, "Query for a key returned more than one entity!"); 
                entity = queriedEntity;
            } 

            value = entity;
            return value != null;
        } 

        private static string QuoteIdentifier(string identifier) 
        { 
            Debug.Assert(identifier != null, "identifier should not be null");
            return "[" + identifier.Replace("]", "]]") + "]"; 
        }

        /// 
        /// Executes the given function on the default container. 
        /// 
        /// Element type for function results. 
        /// Name of function. May include container (e.g. ContainerName.FunctionName) 
        /// or just function name when DefaultContainerName is known.
        ///  
        /// If function is null or empty
        /// If function is invalid (syntax,
        /// does not exist, refers to a function with return type incompatible with T)
        protected ObjectResult ExecuteFunction(string functionName, params ObjectParameter[] parameters) 
            where TElement : IEntityWithChangeTracker //POCO will relax this requirement.
        { 
            EntityUtil.CheckStringArgument(functionName, "function"); 
            EntityUtil.CheckArgumentNull(parameters, "parameters");
 
            for (int i = 0; i < parameters.Length; i++)
            {
                ObjectParameter parameter = parameters[i];
                if (null == parameter) 
                {
                    throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_ExecuteFunctionCalledWithNullParameter(i)); 
                } 
            }
 
            EntityConnection connection = (EntityConnection)this.Connection;
            MetadataWorkspace workspace = this.MetadataWorkspace;

            // find FunctionImport 
            string containerName;
            string functionImportName; 
            CommandHelper.ParseFunctionImportCommandText(functionName, this.DefaultContainerName, 
                out containerName, out functionImportName);
            EdmFunction functionImport = CommandHelper.FindFunctionImport( 
                workspace, containerName, functionImportName);

            // only entity reader imports are supported by this method
            EntityType expectedEntityType; 
            if (!MetadataHelper.TryGetFunctionImportReturnEntityType(functionImport, out expectedEntityType))
            { 
                throw EntityUtil.ExecuteFunctionCalledWithNonReaderFunction(functionImport); 
            }
 
            // check that the type T and function metadata are consistent
            EntityType modelEntityType;
            if (!MetadataHelper.TryDetermineCSpaceModelType(workspace, out modelEntityType) ||
                !modelEntityType.EdmEquals(expectedEntityType)) 
            {
                throw EntityUtil.ExecuteFunctionTypeMismatch(typeof(TElement), expectedEntityType); 
            } 

            // create query 
            EntityCommand entityCommand = new EntityCommand();
            entityCommand.CommandType = CommandType.StoredProcedure;
            entityCommand.CommandText = containerName + "." + functionImportName;
            entityCommand.Connection = connection; 
            if (this.CommandTimeout.HasValue)
            { 
                entityCommand.CommandTimeout = this.CommandTimeout.Value; 
            }
 
            PopulateFunctionEntityCommandParameters(parameters, functionImport, entityCommand);

            return CreateFunctionObjectResult(entityCommand, functionImport.EntitySet, expectedEntityType);
        } 

        private ObjectResult CreateFunctionObjectResult(EntityCommand entityCommand, EntitySet entitySet, EntityType entityType) where TElement : IEntityWithChangeTracker 
        { 
            EnsureConnection();
 
            EntityCommandDefinition commandDefinition = entityCommand.GetCommandDefinition();

            // get store data reader
            DbDataReader storeReader; 
            try
            { 
                storeReader = commandDefinition.ExecuteStoreCommands(entityCommand, CommandBehavior.Default); 
            }
            catch (Exception e) 
            {
                this.ReleaseConnection();
                if (EntityUtil.IsCatchableEntityExceptionType(e))
                { 
                    throw EntityUtil.CommandExecution(System.Data.Entity.Strings.EntityClient_CommandExecutionFailed, e);
                } 
                throw; 
            }
 
            // get materializer
            try
            {
                // create the shaper 
                System.Data.Common.QueryCache.QueryCacheManager cacheManager = this.Perspective.MetadataWorkspace.GetQueryCacheManager();
                ShaperFactory shaperFactory = Translator.TranslateColumnMap(cacheManager, commandDefinition.CreateColumnMap(storeReader), this.MetadataWorkspace, null, MergeOption.AppendOnly, false); 
                Shaper shaper = shaperFactory.Create(storeReader, this, this.MetadataWorkspace, MergeOption.AppendOnly); 
                shaper.OnDone += (object sender, EventArgs e) =>
                { 
                    // consume the store reader
                    CommandHelper.ConsumeReader(storeReader);
                    // trigger event callback
                    entityCommand.NotifyDataReaderClosing(); 
                };
                return new ObjectResult(shaper, entitySet, TypeUsage.Create(entityType)); 
            } 
            catch
            { 
                this.ReleaseConnection();
                storeReader.Dispose();
                throw;
            } 
        }
 
        private void PopulateFunctionEntityCommandParameters(ObjectParameter[] parameters, EdmFunction functionImport, EntityCommand command) 
        {
            // attach entity parameters 
            foreach (ObjectParameter objectParameter in parameters)
            {
                // retrieve parameter information from functionImport
                FunctionParameter functionParameter; 
                if (!functionImport.Parameters.TryGetValue(objectParameter.Name, false, out functionParameter))
                { 
                    functionParameter = null; 
                }
 
                // create new entity parameter
                EntityParameter entityParameter = new EntityParameter();
                entityParameter.ParameterName = objectParameter.Name;
                entityParameter.Value = objectParameter.Value ?? DBNull.Value; 

                if (null != functionParameter) 
                { 
                    entityParameter.Direction = MetadataHelper.ParameterModeToParameterDirection(
                        functionParameter.Mode); 
                }

                if (DBNull.Value == entityParameter.Value ||
                    entityParameter.Direction != ParameterDirection.Input) 
                {
                    TypeUsage typeUsage; 
                    if (null != functionParameter) 
                    {
                        // give precedence to the statically declared type usage 
                        typeUsage = functionParameter.TypeUsage;
                    }
                    else if (null == objectParameter.TypeUsage)
                    { 
                        // since ObjectParameters do not allow users to especify 'facets', make
                        // sure that the parameter typeusage is not populated with the provider 
                        // dafault facet values. 
                        this.Perspective.TryGetTypeByName(objectParameter.MappableType.FullName,
                            false /* bIgnoreCase */, 
                            out typeUsage);
                    }
                    else
                    { 
                        typeUsage = objectParameter.TypeUsage;
                    } 
 
                    // set type information (if the provider cannot determine it from the actual value)
                    DbCommandDefinition.PopulateParameterFromTypeUsage(entityParameter, typeUsage, entityParameter.Direction != ParameterDirection.Input); 
                }

                if (entityParameter.Direction != ParameterDirection.Input)
                { 
                    ParameterBinder binder = new ParameterBinder(entityParameter, objectParameter);
                    command.OnDataReaderClosing += new EventHandler(binder.OnDataReaderClosingHandler); 
                } 
                command.Parameters.Add(entityParameter);
            } 
        }
        #endregion //Methods

        #region Nested types 
        /// 
        /// Supports binding EntityClient parameters to Object Services parameters. 
        ///  
        private class ParameterBinder
        { 
            private readonly EntityParameter _entityParameter;
            private readonly ObjectParameter _objectParameter;

            internal ParameterBinder(EntityParameter entityParameter, ObjectParameter objectParameter) 
            {
                _entityParameter = entityParameter; 
                _objectParameter = objectParameter; 
            }
 
            internal void OnDataReaderClosingHandler(object sender, EventArgs args)
            {
                // When the reader is closing, out/inout parameter values are set on the EntityParameter
                // instance. Pass this value through to the corresponding ObjectParameter. 
                _objectParameter.Value = _entityParameter.Value;
            } 
        } 
        #endregion
    } 
}

// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
//---------------------------------------------------------------------- 
// 
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// 
// 
// @owner       [....]
// @backupOwner [....] 
//--------------------------------------------------------------------- 

using System; 
using System.Collections;
using System.Collections.Generic;
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.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; 

namespace System.Data.Objects 
{ 
    /// 
    /// 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 = null; 
 
        private ObjectQueryProvider _queryProvider;
        #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 
        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
        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);
            }
        } 

        #endregion //Constructors 
 
        #region Properties
        ///  
        /// Gets the connection to the store.
        /// 
        /// If the  instance has been disposed.
        public DbConnection Connection 
        {
            get 
            { 
                if (_connection == null)
                { 
                    throw EntityUtil.ObjectContextDisposed();
                }

                return _connection; 
            }
        } 
 
        /// 
        /// 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.
        ///  
        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 IQueryProvider Provider 
        { 
            get
            { 
                if (null == _queryProvider)
                {
                    _queryProvider = new ObjectQueryProvider(this);
                } 
                return _queryProvider;
            } 
        } 

        #endregion //Properties 

        #region Events
        /// 
        /// 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());
            }
        }
        #endregion //Events 

        #region Methods 
        ///  
        /// AcceptChanges on all associated entries in the ObjectStateManager so their resultant state is either unchanged or detached.
        ///  
        /// 
        public void AcceptAllChanges()
        {
            // 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(); 
            } 
        }
 
        /// 
        /// 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) 
        {
            EntityBid.Trace("\n");
            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.LoadAssemblyForType(entity.GetType(), null); 

            EntitySet entitySet = this.GetEntitySetFromName(entitySetName);

            RelationshipManager relationshipManager = EntityUtil.GetRelationshipManager(entity); 
            bool doCleanup = true;
            try 
            { 
                // Add the root of the graph to the cache.
                AddSingleObject(entitySet, entity, "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 && relationshipManager != null && relationshipManager.Context != null)
                { 
                    // 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.
                    ObjectStateEntry entry = this.ObjectStateManager.FindObjectStateEntry(entity); 
                    if (entry != null && entry.EntityKey.IsTemporary)
                    { 
                        // devnote: relationshipManager is valid, so entity must be IEntityWithRelationships and casting is safe 
                        relationshipManager.NodeVisited = true;
                        IEntityWithRelationships entityWithRelationships = (IEntityWithRelationships)entity; 
                        // 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
                        HashSet promotedEntityKeyRefs = new HashSet(); // no key refs could have been promoted yet
                        RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(entityWithRelationships, promotedEntityKeyRefs); 
                        Debug.Assert(promotedEntityKeyRefs.Count == 0, "Haven't cleaned up all of the promoted reference EntityKeys");
                        RelatedEnd.RemoveEntityFromObjectStateManager(entityWithRelationships); 
                    } 
                    // 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
                } 
            }

            if (relationshipManager != null)
            { 
                relationshipManager.AddRelatedEntitiesToObjectStateManager(/*doAttach*/false);
            } 
        } 
        /// 
        /// 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, object entity, string argumentName) 
        {
            Debug.Assert(entitySet != null, "The extent for an entity must be a non-null entity set."); 
            Debug.Assert(entity != null, "The entity must not be null.");

            // Try to detect if the entity is invalid as soon as possible
            // (before adding the entity to the ObjectStateManager) 
            RelationshipManager relationshipManager = EntityUtil.GetRelationshipManager(entity);
 
            EntityKey key = ObjectContext.FindEntityKey(entity, this); 
            if (null != (object)key)
            { 
                EntityUtil.ValidateEntitySetInKey(key, entitySet);
                key.ValidateEntityKey(entitySet);
            }
 
            this.ObjectStateManager.AddEntry(entity, (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.
            if (relationshipManager != null) 
            {
                relationshipManager.AttachContext(this, entitySet, MergeOption.AppendOnly);
            }
        } 

        ///  
        /// Apply modified properties to the original object. 
        /// 
        /// name of EntitySet of entity to be updated 
        /// object with modified properties
        public void ApplyPropertyChanges(string entitySetName, object changed)
        {
            EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); 
            EntityUtil.CheckArgumentNull(changed, "changed");
 
            // 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.LoadAssemblyForType(changed.GetType(), null);

            EntitySet entitySet = this.GetEntitySetFromName(entitySetName); 

            EntityKey key = ObjectContext.FindEntityKey(changed, this); 
            if (null != (object)key) 
            {
                EntityUtil.ValidateEntitySetInKey(key, entitySet, "entitySetName"); 
                key.ValidateEntityKey(entitySet);
            }
            else
            { 
                key = this.CreateEntityKey(entitySet, changed);
            } 
 
            // Check if entity is already in the cache
            ObjectStateEntry ose = this.ObjectStateManager.FindObjectStateEntry(key); 
            if (ose == null || ose.IsKeyEntry)
            {
                throw EntityUtil.NoEntryExistsForObject(changed);
            } 

            if (ose.State != EntityState.Modified && 
                ose.State != EntityState.Unchanged) 
            {
                throw EntityUtil.EntityMustBeUnchangedOrModified(ose.State); 
            }

            if (ose.Entity.GetType() != changed.GetType())
            { 
                throw EntityUtil.EntitiesHaveDifferentType(ose.Entity.GetType().FullName, changed.GetType().FullName);
            } 
 
            ose.CompareKeyProperties(changed);
 
            Shaper.UpdateRecord(changed, ose.CurrentValues);
        }

 
        /// 
        /// 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)
        {
            EntityBid.Trace("\n"); 
            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.LoadAssemblyForType(entity.GetType(), null);

            // Find entity set using given entity set name 
            EntitySet entitySetFromName = null;
            if (!String.IsNullOrEmpty(entitySetName)) 
            { 
                entitySetFromName = this.GetEntitySetFromName(entitySetName);
            } 

            // Find entity set using entity key
            EntitySet entitySetFromKey = null;
            EntityKey key = ObjectContext.FindEntityKey(entity, this); 
            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 entitySet = entitySetFromKey ?? entitySetFromName;
 
            // Check if entity set was found
            if (entitySet == null)
            {
                throw EntityUtil.EntitySetNameOrEntityKeyRequired(); 
            }
 
            this.ValidateEntitySet(entitySet, entity.GetType()); 

            // Check if entity is already in the cache 
            ObjectStateEntry existingEntry = this.ObjectStateManager.FindObjectStateEntry(key);
            if (null != existingEntry && !existingEntry.IsKeyEntry)
            {
                if (!Object.ReferenceEquals(existingEntry.Entity, entity)) 
                {
                    throw EntityUtil.ObjectStateManagerContainsThisEntityKey(); 
                } 
                else
                { 
                    if (existingEntry.State != EntityState.Unchanged)
                    {
                        throw EntityUtil.EntityAlreadyExistsInObjectStateManager();
                    } 
                    else
                    { 
                        // 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
                        return; 
                    }
                }
            }
 
            this.ObjectStateManager.BeginAttachTracking();
 
            try 
            {
                RelationshipManager relationshipManager = EntityUtil.GetRelationshipManager(entity); 
                bool doCleanup = true;
                try
                {
                    // Attach the root of entity graph to the cache. 
                    AttachSingleObject(entity, entitySet, "entity");
                    doCleanup = false; 
                } 
                finally
                { 
                    // SQLBU 555615 Be sure that relationshipManager.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 && relationshipManager != null && relationshipManager.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) 

                        // devnote: relationshipManager is valid, so entity must be IEntityWithRelationships and casting is safe 
                        relationshipManager.NodeVisited = true; 
                        IEntityWithRelationships entityWithRelationships = (IEntityWithRelationships)entity;
                        // 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.
                        HashSet promotedEntityKeyRefs = new HashSet(); // no key refs could have been promoted yet
                        RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(entityWithRelationships, promotedEntityKeyRefs);
                        Debug.Assert(promotedEntityKeyRefs.Count == 0, "Haven't cleaned up all of the promoted reference EntityKeys"); 
                        RelatedEnd.RemoveEntityFromObjectStateManager(entityWithRelationships);
                    } 
                } 

                if (relationshipManager != null) 
                {
                    relationshipManager.AddRelatedEntitiesToObjectStateManager(/*doAttach*/true);
                }
            } 
            finally
            { 
                this.ObjectStateManager.EndAttachTracking(); 
            }
        } 
        /// 
        /// 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(object entity, EntitySet entitySet, string argumentName) 
        { 
            Debug.Assert(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 = EntityUtil.GetRelationshipManager(entity); 

            EntityKey key = ObjectContext.FindEntityKey(entity, this); 
            if (null != (object)key) 
            {
                EntityUtil.ValidateEntitySetInKey(key, entitySet); 
                key.ValidateEntityKey(entitySet);
            }
            else
            { 
                key = this.CreateEntityKey(entitySet, entity);
            } 
 
            Debug.Assert(key != null, "GetEntityKey should have returned a non-null key");
 
            // Temporary keys are not allowed
            if (key.IsTemporary)
            {
                throw EntityUtil.CannotAttachEntityWithTemporaryKey(); 
            }
 
            IEntityWithKey entityWithKey = entity as IEntityWithKey; 
            if (null != (object)entityWithKey && null == (object)entityWithKey.EntityKey)
            { 
                EntityUtil.SetKeyOntoEntity(entity, key);
            }

            // Check if entity already exists in the cache. 
            // NOTE: This check could be done earlier, but this way I avoid creating key twice.
            ObjectStateEntry existingEntry = ObjectStateManager.FindObjectStateEntry(key); 
 
            if (null != existingEntry)
            { 
                if (existingEntry.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(existingEntry, entity, /*shadowValues*/ null, /*replacingEntry*/ false);

                    if (relationshipManager != null)
                    { 
                        relationshipManager.AttachContext(this, entitySet, MergeOption.AppendOnly);
                    } 
                    this.ObjectStateManager.PromoteKeyEntry(existingEntry, entity, /*shadowValues*/ null, /*replacingEntry*/ false, /*setIsLoaded*/ false, /*keyEntryInitialized*/ true, "Attach"); 
                    if (relationshipManager != null)
                    { 
                        relationshipManager.CheckReferentialConstraintProperties(key);
                    }
                }
                else 
                {
                    Debug.Assert(!Object.ReferenceEquals(existingEntry.Entity, entity)); 
                    throw EntityUtil.ObjectStateManagerContainsThisEntityKey(); 
                }
            } 
            else
            {
                this.ObjectStateManager.AttachEntry(key, entity, entitySet, argumentName);
                if (relationshipManager != null) 
                {
                    relationshipManager.AttachContext(this, entitySet, MergeOption.AppendOnly); 
                    relationshipManager.CheckReferentialConstraintProperties(key); 
                }
            } 
        }

        /// 
        /// 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) 
        {
            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.LoadAssemblyForType(entity.GetType(), null); 

            EntitySet entitySet = this.GetEntitySetFromName(entitySetName);

            return this.CreateEntityKey(entitySet, entity); 
        }
 
        internal EntityKey CreateEntityKey(EntitySet entitySet, object entity) 
        {
            Debug.Assert(entitySet != null, "null entitySet"); 
            Debug.Assert(entity != null, "null entity");

            // Creates an EntityKey based on the values in the entity and the given EntitySet
            ReadOnlyMetadataCollection keyMembers = entitySet.ElementType.KeyMembers; 
            StateManagerTypeMetadata typeMetadata = ObjectStateManager.GetOrAddStateManagerTypeMetadata(entity.GetType(), entitySet);
            object[] keyValues = new object[keyMembers.Count]; 
 
            for (int i = 0; i < keyMembers.Count; ++i)
            { 
                string keyName = keyMembers[i].Name;
                int ordinal = typeMetadata.GetOrdinalforCLayerMemberName(keyName);
                if (ordinal < 0)
                { 
                    throw EntityUtil.EntityTypeDoesNotMatchEntitySet(entity.GetType().FullName, entitySet.Name, "entity");
                } 
 
                keyValues[i] = typeMetadata.Member(ordinal).GetValue(entity);
            } 

            if (keyValues.Length == 1)
            {
                return new EntityKey(entitySet, keyValues[0]); 
            }
            else 
            { 
                return new EntityKey(entitySet, keyValues);
            } 
        }

        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, Dictionary entities, Dictionary> currentKeys)
        { 
            if (null == entityLike) 
            {
                throw EntityUtil.NthElementIsNull(entities.Count); 
            }

            EntityKey key = ObjectContext.FindEntityKey(entityLike, this);
            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);
        } 

        #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  instance has been disposed.
        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; 
            }

        }
 
        /// 
        /// 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  instance has been disposed. 
        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

 
        /// 
        /// 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 ObjectQuery CreateQuery(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.LoadAssemblyForType(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
        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  instance has been disposed.
        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; 
        }
        ///  
        /// Marks an object for deletion from the cache. 
        /// 
        /// Object to be deleted. 
        public void DeleteObject(object entity)
        {
            EntityBid.Trace("\n");
            EntityUtil.CheckArgumentNull(entity, "entity"); 

            ObjectStateEntry cacheEntry = this.ObjectStateManager.FindObjectStateEntry(entity); 
            if (cacheEntry == null || !object.ReferenceEquals(cacheEntry.Entity, entity)) 
            {
                throw EntityUtil.CannotDeleteEntityNotInObjectStateManager(); 
            }

            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) 
        {
            EntityBid.Trace("\n"); 
            EntityUtil.CheckArgumentNull(entity, "entity"); 

            ObjectStateEntry cacheEntry = this.ObjectStateManager.FindObjectStateEntry(entity); 
            if (cacheEntry == null ||
                !object.ReferenceEquals(cacheEntry.Entity, entity) ||
                cacheEntry.Entity == null) // this condition includes key entries and relationship entries
            { 
                throw EntityUtil.CannotDetachEntityNotInObjectStateManager();
            } 
 
            cacheEntry.Detach();
        } 

        /// 
        /// Disposes this ObjectContext.
        ///  
        public void Dispose()
        { 
            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;
            }
            // 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 = null; 
            if (!this.Perspective.TryGetType(entityType, out entityTypeUsage) || 
                !TypeSemantics.IsEntityType(entityTypeUsage))
            { 
                throw EntityUtil.InvalidEntityType("entity", entityType);
            }
            if (!entitySet.ElementType.IsAssignableFrom(entityTypeUsage.EdmType))
            { 
                throw EntityUtil.InvalidEntitySetOnEntity(entitySet.Name, entityType, "entity");
            } 
        } 
        #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.LoadFromEntityType(entitySet.ElementType, System.Reflection.Assembly.GetCallingAssembly()); 

            object entity;
            if (!TryGetObjectByKey(key, out entity))
            { 
                throw EntityUtil.ObjectNotFound();
            } 
            return entity; 
        }
 
        /// 
        /// Returns the key on an entity.
        /// Used in circumstances in which the context.ObjectStateManager might be null.
        ///  
        /// 
        ///  
        static internal EntityKey FindEntityKey(object entity, ObjectContext context) 
        {
            IEntityWithKey entityWithKey = entity as IEntityWithKey; 
            if (null != entityWithKey)
            {
                return entityWithKey.EntityKey;
            } 
            if (null != context._cache)
            { 
                EntityKey key; 
                if (context.ObjectStateManager.TryGetEntityKey(entity, out key))
                { 
                    return key;
                }
            }
            return null; 
        }
 
        #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);
            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); 
            }
        } 
        ///  
        /// 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) 
        { 
            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);
            }
        }
 
        private void RefreshCheck(
            Dictionary entities, 
            object entity, EntityKey key) 
        {
            Debug.Assert(entity != null, "The entity is null."); 

            ObjectStateEntry entry = ObjectStateManager.FindObjectStateEntry(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) 
                        {
                            item.Value.Delete(); 
                            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;

            // Initialize the command tree used to build the refresh query.
            DbQueryCommandTree tree = new DbQueryCommandTree(this.MetadataWorkspace, DataSpace.CSpace); 

            // Bind the target EntitySet under the name "EntitySet". 
            DbExpressionBinding entitySetBinding = tree.CreateExpressionBinding(tree.CreateScanExpression(targetSet), "EntitySet"); 

            // Use the variable from the set binding as the 'e' in a new GetRefKey(GetEntityRef(e)) expression. 
            DbExpression boundEntityKey = tree.CreateRefKeyExpression(tree.CreateEntityRefExpression(entitySetBinding.Variable));

            // Create a new VariableReference expression with which to refer to the key values
            // of the current entity from within the 'where' predicate of the refresh query. 
            // This will later be bound to GetRefKey(GetEntityRef(e)) by an enclosing LambdaFunction.
            DbVariableReferenceExpression sourceEntityKeyVarRef = tree.CreateVariableReferenceExpression("EntityKey", boundEntityKey.ResultType); 
 
            // 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(tree, targetSet);
                DbExpression keyFilter = tree.CreateNewRowExpression(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] = tree.CreateEqualsExpression(sourceEntityKeyVarRef, 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, tree.CreateOrExpression);
 
            //
            // Create a new LambdaFunctionExpression that binds GetRefKey(GetEntityRef("EntitySet")) 
            // to the bound entity key variable name, "EntityKey" and uses the predicate expression 
            // build above as its Lambda body expression.
            // This correctly binds the variable used in the predicate. 
            //
            KeyValuePair[] lambdaFormals = new KeyValuePair[1];
            lambdaFormals[0] = new KeyValuePair(sourceEntityKeyVarRef.VariableName, sourceEntityKeyVarRef.ResultType);
 
            DbExpression[] lambdaArgs = new DbExpression[1];
            lambdaArgs[0] = boundEntityKey; 
 
            entitySetFilter = tree.CreateLambdaFunctionExpression(lambdaFormals, entitySetFilter, lambdaArgs);
 
            // 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.
            tree.Query = tree.CreateFilterExpression(entitySetBinding, entitySetFilter);
 
            // 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 results = ObjectQueryExecutionPlan.ExecuteCommandTree(this, tree, mergeOption); 
 
                foreach (object entity in results)
                { 
                    // There is a risk that, during an event, the Entity removed itself from the cache.
                    ObjectStateEntry entry = ObjectStateManager.FindObjectStateEntry(entity);
                    if ((null != entry) && (EntityState.Modified == entry.State))
                    {   // this is 'ForceChanges' - which is the same as PreserveChanges, except all properties are marked modified. 
                        Debug.Assert(RefreshMode.ClientWins == refreshMode, "StoreWins always becomes unchanged");
                        entry.SetModifiedAll(); 
                    } 

                    EntityKey key = this.ObjectStateManager.GetEntityKey(entity); 
                    bool flag = trackedEntities.Remove(key);
                    Debug.Assert(flag, "Refreshed entity not in collection");
                }
            } 
            catch
            { 
                // Enumeration did not complete, so the connection must be explicitly released. 
                this.ReleaseConnection();
                throw; 
            }

            // Return the position in the list from which the next refresh operation should start.
            // This will be equal to the list count if all remaining entities in the list were 
            // refreshed during this call.
            return startFrom; 
        } 

        private static int RefreshEntitiesSize(IEnumerable collection) 
        {
            ICollection list = collection as ICollection;
            return ((null != list) ? list.Count : 0);
        } 
        #endregion
 
        #region SaveChanges 
        /// 
        /// Persists all updates to the store. 
        /// 
        /// 
        ///   the number of dirty (i.e., Added, Modified, or Deleted) ObjectStateEntries
        ///   in the ObjectStateManager when SaveChanges was called. 
        /// 
        public Int32 SaveChanges() 
        { 
            return SaveChanges(true);
        } 

        /// 
        /// Persists all updates to the store.
        ///  
        /// if false, user must call AcceptAllChanges/>
        ///  
        ///   the number of dirty (i.e., Added, Modified, or Deleted) ObjectStateEntries 
        ///   in the ObjectStateManager when SaveChanges was called.
        ///  
        public Int32 SaveChanges(bool acceptChangesDuringSave)
        {
            OnSavingChanges();
 
            bool mustReleaseConnection = false;
            Int32 entriesAffected = ObjectStateManager.GetObjectStateEntriesCount(EntityState.Added | EntityState.Deleted | EntityState.Modified); 
            using (new EntityBid.ScopeAuto(" %d#, affectingEntries=%d", ObjectID, entriesAffected)) 
            {
                EntityConnection connection = (EntityConnection)Connection; 

                if (0 < entriesAffected)
                {   // else fast exit if no changes to save to avoids interacting with or starting of new transactions
 
                    // get data adapter
                    if (_adapter == null) 
                    { 
                        IServiceProvider sp = connection.ProviderFactory as IServiceProvider;
                        if (sp != null) 
                        {
                            _adapter = sp.GetService(typeof(IEntityAdapter)) as IEntityAdapter;
                        }
                        if (_adapter == null) 
                        {
                            throw EntityUtil.InvalidDataAdapter(); 
                        } 
                    }
                    // only accept changes after the local transaction commits 
                    _adapter.AcceptChangesDuringUpdate = false;
                    _adapter.Connection = connection;
                    _adapter.CommandTimeout = this.CommandTimeout;
 
                    try
                    { 
                        EnsureConnection(); 
                        mustReleaseConnection = true;
 
                        // determine what transaction to enlist in
                        Transaction currentTransaction = Transaction.Current;
                        bool needLocalTransaction = false;
                        if (null == connection.CurrentTransaction) 
                        {
                            // If there isn't a local transaction, we'll attempt to enlist on the 
                            // current SysTx transaction so we don't need to construct a local 
                            // transaction.
 

                            needLocalTransaction = (null == _lastTransaction);
                        }
                        // else user already has their own local transaction going; user will do the abort or commit. 

                        DbTransaction localTransaction = null; 
                        try 
                        {
                            // EntityConnection tracks the CurrentTransaction we don't need to pass it around 
                            if (needLocalTransaction)
                            {
                                localTransaction = connection.BeginTransaction();
                            } 
                            entriesAffected = _adapter.Update(ObjectStateManager);
 
                            if (null != localTransaction) 
                            {   // we started the local transaction; so we also commit it
                                localTransaction.Commit(); 
                            }
                            // else on success with no exception is thrown, user generally commits the transaction
                        }
                        finally 
                        {
                            if (null != localTransaction) 
                            {   // we started the local transaction; so it requires disposal (rollback if not previously committed 
                                localTransaction.Dispose();
                            } 
                            // else on failure with an exception being thrown, user generally aborts (default action with transaction without an explict commit)
                        }
                    }
                    finally 
                    {
                        if (mustReleaseConnection) 
                        { 
                            // Release the connection when we are done with the save
                            ReleaseConnection(); 
                        }
                    }

                    if (acceptChangesDuringSave) 
                    {   // only accept changes after the local transaction commits
 
                        try 
                        {
                            AcceptAllChanges(); 
                        }
                        catch (Exception e)
                        {
                            // If AcceptAllChanges throw - let's inform user that changes in database were committed 
                            // and that Context and Database can be in inconsistent state.
 
                            // We should not be wrapping all exceptions 
                            if (EntityUtil.IsCatchableExceptionType(e))
                            { 
                                throw EntityUtil.AcceptAllChangesFailure(e);
                            }
                            throw;
                        } 
                    }
                } 
            } 
            return entriesAffected;
        } 
        #endregion

        /// 
        /// Attempts to retrieve an object from the cache or the store. 
        /// 
        /// Key of the object to be found. 
        /// Out param for the object. 
        /// True if the object was found, false otherwise.
        public bool TryGetObjectByKey(EntityKey key, out object value) 
        {
            // try the cache first
            ObjectStateEntry entry;
            ObjectStateManager.TryGetObjectStateEntry(key, out entry); // this will check key argument 
            if (entry != null)
            { 
                // can't find keys 
                if (!entry.IsKeyEntry)
                { 
                    // SQLBUDT 511296 returning deleted object.
                    value = entry.Entity;
                    return value != null;
                } 
            }
 
            if (key.IsTemporary) 
            {
                // If the key is temporary, we cannot find a corresponding object in the store. 
                value = null;
                return false;
            }
 
            EntitySet entitySet = key.GetEntitySet(this.MetadataWorkspace);
            Debug.Assert(entitySet != null, "Key's EntitySet should not be null in the MetadataWorkspace"); 
 
            // Validate the EntityKey values against the EntitySet
            key.ValidateEntityKey(entitySet, true /*isArgumentException*/, "key"); 

            // 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.LoadFromEntityType(entitySet.ElementType, System.Reflection.Assembly.GetCallingAssembly()); 
 
            // Execute the query:
            // SELECT VALUE X FROM [EC].[ES] AS X 
            // WHERE X.KeyProp0 = @p0 AND X.KeyProp1 = @p1 AND ...
            // parameters are the key values

            // Build the Entity SQL query 
            StringBuilder esql = new StringBuilder();
            esql.AppendFormat("SELECT VALUE X FROM {0}.{1} AS X WHERE ", QuoteIdentifier(entitySet.EntityContainer.Name), QuoteIdentifier(entitySet.Name)); 
            EntityKeyMember[] members = key.EntityKeyValues; 
            ReadOnlyMetadataCollection keyMembers = entitySet.ElementType.KeyMembers;
            ObjectParameter[] parameters = new ObjectParameter[members.Length]; 

            for(int i =0; i< members.Length; i++)
            {
                if (i > 0) 
                {
                    esql.Append(" AND "); 
                } 
                string parameterName = string.Format(CultureInfo.InvariantCulture, "p{0}", i.ToString(CultureInfo.InvariantCulture));
                esql.AppendFormat("X.{0} = @{1}", QuoteIdentifier(members[i].Key), parameterName); 
                parameters[i] = new ObjectParameter(parameterName, members[i].Value);

                // Try to set the TypeUsage on the ObjectParameter
                EdmMember keyMember = null; 
                if (keyMembers.TryGetValue(members[i].Key, true, out keyMember))
                { 
                    parameters[i].TypeUsage = keyMember.TypeUsage; 
                }
            } 

            // Execute the query
            object entity = null;
            ObjectResult results = CreateQuery(esql.ToString(), parameters).Execute(MergeOption.AppendOnly); 
            foreach (object queriedEntity in results)
            { 
                Debug.Assert(entity == null, "Query for a key returned more than one entity!"); 
                entity = queriedEntity;
            } 

            value = entity;
            return value != null;
        } 

        private static string QuoteIdentifier(string identifier) 
        { 
            Debug.Assert(identifier != null, "identifier should not be null");
            return "[" + identifier.Replace("]", "]]") + "]"; 
        }

        /// 
        /// Executes the given function on the default container. 
        /// 
        /// Element type for function results. 
        /// Name of function. May include container (e.g. ContainerName.FunctionName) 
        /// or just function name when DefaultContainerName is known.
        ///  
        /// If function is null or empty
        /// If function is invalid (syntax,
        /// does not exist, refers to a function with return type incompatible with T)
        protected ObjectResult ExecuteFunction(string functionName, params ObjectParameter[] parameters) 
            where TElement : IEntityWithChangeTracker //POCO will relax this requirement.
        { 
            EntityUtil.CheckStringArgument(functionName, "function"); 
            EntityUtil.CheckArgumentNull(parameters, "parameters");
 
            for (int i = 0; i < parameters.Length; i++)
            {
                ObjectParameter parameter = parameters[i];
                if (null == parameter) 
                {
                    throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_ExecuteFunctionCalledWithNullParameter(i)); 
                } 
            }
 
            EntityConnection connection = (EntityConnection)this.Connection;
            MetadataWorkspace workspace = this.MetadataWorkspace;

            // find FunctionImport 
            string containerName;
            string functionImportName; 
            CommandHelper.ParseFunctionImportCommandText(functionName, this.DefaultContainerName, 
                out containerName, out functionImportName);
            EdmFunction functionImport = CommandHelper.FindFunctionImport( 
                workspace, containerName, functionImportName);

            // only entity reader imports are supported by this method
            EntityType expectedEntityType; 
            if (!MetadataHelper.TryGetFunctionImportReturnEntityType(functionImport, out expectedEntityType))
            { 
                throw EntityUtil.ExecuteFunctionCalledWithNonReaderFunction(functionImport); 
            }
 
            // check that the type T and function metadata are consistent
            EntityType modelEntityType;
            if (!MetadataHelper.TryDetermineCSpaceModelType(workspace, out modelEntityType) ||
                !modelEntityType.EdmEquals(expectedEntityType)) 
            {
                throw EntityUtil.ExecuteFunctionTypeMismatch(typeof(TElement), expectedEntityType); 
            } 

            // create query 
            EntityCommand entityCommand = new EntityCommand();
            entityCommand.CommandType = CommandType.StoredProcedure;
            entityCommand.CommandText = containerName + "." + functionImportName;
            entityCommand.Connection = connection; 
            if (this.CommandTimeout.HasValue)
            { 
                entityCommand.CommandTimeout = this.CommandTimeout.Value; 
            }
 
            PopulateFunctionEntityCommandParameters(parameters, functionImport, entityCommand);

            return CreateFunctionObjectResult(entityCommand, functionImport.EntitySet, expectedEntityType);
        } 

        private ObjectResult CreateFunctionObjectResult(EntityCommand entityCommand, EntitySet entitySet, EntityType entityType) where TElement : IEntityWithChangeTracker 
        { 
            EnsureConnection();
 
            EntityCommandDefinition commandDefinition = entityCommand.GetCommandDefinition();

            // get store data reader
            DbDataReader storeReader; 
            try
            { 
                storeReader = commandDefinition.ExecuteStoreCommands(entityCommand, CommandBehavior.Default); 
            }
            catch (Exception e) 
            {
                this.ReleaseConnection();
                if (EntityUtil.IsCatchableEntityExceptionType(e))
                { 
                    throw EntityUtil.CommandExecution(System.Data.Entity.Strings.EntityClient_CommandExecutionFailed, e);
                } 
                throw; 
            }
 
            // get materializer
            try
            {
                // create the shaper 
                System.Data.Common.QueryCache.QueryCacheManager cacheManager = this.Perspective.MetadataWorkspace.GetQueryCacheManager();
                ShaperFactory shaperFactory = Translator.TranslateColumnMap(cacheManager, commandDefinition.CreateColumnMap(storeReader), this.MetadataWorkspace, null, MergeOption.AppendOnly, false); 
                Shaper shaper = shaperFactory.Create(storeReader, this, this.MetadataWorkspace, MergeOption.AppendOnly); 
                shaper.OnDone += (object sender, EventArgs e) =>
                { 
                    // consume the store reader
                    CommandHelper.ConsumeReader(storeReader);
                    // trigger event callback
                    entityCommand.NotifyDataReaderClosing(); 
                };
                return new ObjectResult(shaper, entitySet, TypeUsage.Create(entityType)); 
            } 
            catch
            { 
                this.ReleaseConnection();
                storeReader.Dispose();
                throw;
            } 
        }
 
        private void PopulateFunctionEntityCommandParameters(ObjectParameter[] parameters, EdmFunction functionImport, EntityCommand command) 
        {
            // attach entity parameters 
            foreach (ObjectParameter objectParameter in parameters)
            {
                // retrieve parameter information from functionImport
                FunctionParameter functionParameter; 
                if (!functionImport.Parameters.TryGetValue(objectParameter.Name, false, out functionParameter))
                { 
                    functionParameter = null; 
                }
 
                // create new entity parameter
                EntityParameter entityParameter = new EntityParameter();
                entityParameter.ParameterName = objectParameter.Name;
                entityParameter.Value = objectParameter.Value ?? DBNull.Value; 

                if (null != functionParameter) 
                { 
                    entityParameter.Direction = MetadataHelper.ParameterModeToParameterDirection(
                        functionParameter.Mode); 
                }

                if (DBNull.Value == entityParameter.Value ||
                    entityParameter.Direction != ParameterDirection.Input) 
                {
                    TypeUsage typeUsage; 
                    if (null != functionParameter) 
                    {
                        // give precedence to the statically declared type usage 
                        typeUsage = functionParameter.TypeUsage;
                    }
                    else if (null == objectParameter.TypeUsage)
                    { 
                        // since ObjectParameters do not allow users to especify 'facets', make
                        // sure that the parameter typeusage is not populated with the provider 
                        // dafault facet values. 
                        this.Perspective.TryGetTypeByName(objectParameter.MappableType.FullName,
                            false /* bIgnoreCase */, 
                            out typeUsage);
                    }
                    else
                    { 
                        typeUsage = objectParameter.TypeUsage;
                    } 
 
                    // set type information (if the provider cannot determine it from the actual value)
                    DbCommandDefinition.PopulateParameterFromTypeUsage(entityParameter, typeUsage, entityParameter.Direction != ParameterDirection.Input); 
                }

                if (entityParameter.Direction != ParameterDirection.Input)
                { 
                    ParameterBinder binder = new ParameterBinder(entityParameter, objectParameter);
                    command.OnDataReaderClosing += new EventHandler(binder.OnDataReaderClosingHandler); 
                } 
                command.Parameters.Add(entityParameter);
            } 
        }
        #endregion //Methods

        #region Nested types 
        /// 
        /// Supports binding EntityClient parameters to Object Services parameters. 
        ///  
        private class ParameterBinder
        { 
            private readonly EntityParameter _entityParameter;
            private readonly ObjectParameter _objectParameter;

            internal ParameterBinder(EntityParameter entityParameter, ObjectParameter objectParameter) 
            {
                _entityParameter = entityParameter; 
                _objectParameter = objectParameter; 
            }
 
            internal void OnDataReaderClosingHandler(object sender, EventArgs args)
            {
                // When the reader is closing, out/inout parameter values are set on the EntityParameter
                // instance. Pass this value through to the corresponding ObjectParameter. 
                _objectParameter.Value = _entityParameter.Value;
            } 
        } 
        #endregion
    } 
}

// File provided for Reference Use Only by Microsoft Corporation (c) 2007.

                        

                        

Link Menu

Network programming in C#, Network Programming in VB.NET, Network Programming in .NET
This book is available now!
Buy at Amazon US or
Buy at Amazon UK