public virtual object GetEntity(IEntityType entityType, IValueReader valueReader)
        {
            Check.NotNull(entityType, "entityType");
            Check.NotNull(valueReader, "valueReader");

            var keyProperties = entityType.GetPrimaryKey().Properties;

            var entityKey
                = _entityKeyFactorySource
                  .GetKeyFactory(keyProperties)
                  .Create(entityType, keyProperties, valueReader);

            var stateEntry = _stateManager.TryGetEntry(entityKey);

            if (stateEntry == null &&
                !_stateEntriesByEntityKey.TryGetValue(entityKey, out stateEntry))
            {
                stateEntry = _stateEntryFactory.Create(entityType, valueReader);

                _stateEntriesByEntityKey.Add(entityKey, stateEntry);
                _stateEntriesByEntityInstance.Add(stateEntry.Entity, stateEntry);
            }

            return(stateEntry.Entity);
        }
        public virtual object GetEntity(IEntityType entityType, IValueReader valueReader, bool queryStateManager)
        {
            Check.NotNull(entityType, "entityType");
            Check.NotNull(valueReader, "valueReader");

            var keyProperties
                = entityType.GetPrimaryKey().Properties;

            var entityKey
                = _entityKeyFactorySource
                  .GetKeyFactory(keyProperties)
                  .Create(entityType, keyProperties, valueReader);

            if (entityKey == EntityKey.NullEntityKey)
            {
                return(null);
            }

            var stateEntry = _stateManager.TryGetEntry(entityKey);

            if (queryStateManager && stateEntry != null)
            {
                return(stateEntry.Entity);
            }

            BufferedEntity bufferedEntity;

            if (!_byEntityKey.TryGetValue(entityKey, out bufferedEntity))
            {
                bufferedEntity
                    = new BufferedEntity(entityType, valueReader)
                    {
                    // TODO: Optimize this by not materializing when not required for query execution. i.e.
                    //       entity is only needed in final results
                    Instance = _materializerSource.GetMaterializer(entityType)(valueReader)
                    };

                _byEntityKey.Add(entityKey, bufferedEntity);
                _byEntityInstance.Add(bufferedEntity.Instance, new List <BufferedEntity> {
                    bufferedEntity
                });
            }

            return(bufferedEntity.Instance);
        }