public void Prepare_returns_a_new_instance()
        {
            var objectQueryExecutionPlanFactory = new ObjectQueryExecutionPlanFactory(
                Common.Internal.Materialization.MockHelper.CreateTranslator<object>());

            var metadataWorkspace = new MetadataWorkspace();
            var edmItemCollection = new EdmItemCollection();
            metadataWorkspace.RegisterItemCollection(edmItemCollection);
            metadataWorkspace.RegisterItemCollection(new ObjectItemCollection());
            var fakeSqlProviderManifest = new FakeSqlProviderServices().GetProviderManifest("2008");
            var storeItemCollection = new StoreItemCollection(FakeSqlProviderFactory.Instance, fakeSqlProviderManifest, "2008");
            metadataWorkspace.RegisterItemCollection(storeItemCollection);
            metadataWorkspace.RegisterItemCollection(new StorageMappingItemCollection(edmItemCollection, storeItemCollection, Enumerable.Empty<XmlReader>()));

            var fakeSqlConnection = new FakeSqlConnection();
            fakeSqlConnection.ConnectionString = "foo";
            var entityConnection = new EntityConnection(metadataWorkspace, fakeSqlConnection, false);

            var objectContext = new ObjectContext(entityConnection);
            var dbExpression = new DbNullExpression(TypeUsage.Create(fakeSqlProviderManifest.GetStoreTypes().First()));
            var dbQueryCommandTree = new DbQueryCommandTree(metadataWorkspace, DataSpace.CSpace,
               dbExpression, validate: false);
            var parameters = new List<Tuple<ObjectParameter, QueryParameterExpression>>();

            var objectQueryExecutionPlan = objectQueryExecutionPlanFactory.Prepare(objectContext, dbQueryCommandTree, typeof(object),
                MergeOption.NoTracking, new Span(), parameters, aliasGenerator: null);

            Assert.NotNull(objectQueryExecutionPlan);
        }
        public virtual bool Opening(EntityConnection entityConnection, DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(entityConnection);
            DebugCheck.NotNull(interceptionContext);

            return _internalDispatcher.Dispatch(true, (b, i) => i.ConnectionOpening(entityConnection, interceptionContext) && b);
        }
 // <summary>
 // Constructs the DbContextTransaction object with the associated transaction object
 // </summary>
 // <param name="transaction">The EntityTransaction object to use</param>
 internal DbContextTransaction(EntityTransaction transaction)
 {
     DebugCheck.NotNull(transaction);
     _connection = transaction.Connection;
     EnsureOpenConnection();
     _entityTransaction = transaction;
 }
        static void Main(string[] args)
        {


            EntityConnection cn = new EntityConnection("name=ASIEntities7");
            DbConnection dbcn = new SqlConnection( System.Configuration.ConfigurationManager.ConnectionStrings["base dados"].ConnectionString );

            var alnPedro = new Aluno { NumAl = 1001, Nome = "Pedro" };
            alnPedro.AlunosAssEsts = new HashSet<AlunosAssEst>();

            var alnPaula = new Aluno { NumAl = 1002, Nome = "Paula" };
            alnPaula.AlunosAssEsts = new HashSet<AlunosAssEst>();

            using (var ctx1 = new ASIEntities7(cn))
            {
                // em alternativa a usar o Sql Server Profiler, pode fazer:
                //ctx1.Database.Log = Console.Write;

                ctx1.Alunos.Add(alnPedro);
                ctx1.Alunos.Add(alnPaula);

                // ExecuteDML(dbcn, "A trocar as voltas ao EF6 inserindo o Jose ADO.Net(1001)...", "INSERT INTO [BD3_1].[dbo].[Alunos] ([NumAl],[Nome]) VALUES (1001, 'Jose ADO.Net')");
                SaveContextChanges(ctx1, PoliticaConcorrencia.UsarInfoBD);
            }
            
            using (var ctxPessimista = new ASIEntities7(cn))
            {
                // em alternativa a usar o Sql Server Profiler, pode fazer:
                //ctx4.Database.Log = Console.Write;

                Aluno alnPedroCtx = (from a in ctxPessimista.Alunos where a.NumAl == 1001 select a).First();
                alnPedroCtx.Nome = "Pedro ContextoEF6";

                ExecuteDML(dbcn, "O ADO.Net vai mudar o nome do Pedro para 'Pedro ADO.Net'.", "UPDATE [BD3_1].[dbo].[Alunos] SET [Nome] = 'Pedro ADO.Net' WHERE [NumAl] = 1001");
                
                Console.WriteLine("O EF6 vai mudar o nome do Pedro para 'Pedro ContextoEF6'. Antes de gravar, alnPedroCtx.Nome = {0}", alnPedroCtx.Nome);
                SaveContextChanges(ctxPessimista, PoliticaConcorrencia.UsarInfoBD);
                Console.WriteLine("Depois de gravadas as alteracoes com uma politica pessimista (vale o que esta na BD), o nome do Pedro no ambito do contexto EF6 é: alnPedroCtx.Nome = {0})", alnPedroCtx.Nome);
            }

            Console.WriteLine();

            using (var ctxOptimista = new ASIEntities7(cn))
            {
                // em alternativa a usar o Sql Server Profiler, pode fazer:
                //ctx5.Database.Log = Console.Write;

                Aluno alnPedroCtx = (from a in ctxOptimista.Alunos where a.NumAl == 1001 select a).First();
                alnPedroCtx.Nome = "Pedro ContextoEF6";

                ExecuteDML(dbcn, "O ADO.Net vai mudar o nome do Pedro para 'Pedro ADO.Net Outra Vez'.", "UPDATE [BD3_1].[dbo].[Alunos] SET [Nome] = 'Pedro ADO.Net Outra Vez' WHERE [NumAl] = 1001");
                
                Console.WriteLine("O EF6 vai mudar o nome do Pedro para 'Pedro ContextoEF6'. Antes de gravar, alnPedroCtx.Nome = {0}", alnPedroCtx.Nome);
                SaveContextChanges(ctxOptimista, PoliticaConcorrencia.UsarInfoCtx);
                Console.WriteLine("Depois de gravadas as alteracoes com uma politica optimista (vale o que esta no Contexto), o nome do Pedro no ambito do contexto EF6 é: alnPedroCtx.Nome = {0})", alnPedroCtx.Nome);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
 /// <summary>
 ///     Constructs the DbContextTransaction object with the associated connection object
 ///     and with the given isolation level
 /// </summary>
 /// <param name="connection">The EntityConnection object owning this transaction </param>
 /// <param name="isolationLevel">The database isolation level with which the underlying store transaction will be created</param>
 internal DbContextTransaction(EntityConnection connection, IsolationLevel isolationLevel)
 {
     DebugCheck.NotNull(connection);
     _connection = connection;
     EnsureOpenConnection();
     _entityTransaction = _connection.BeginTransaction(isolationLevel);
 }
Exemple #6
0
        public void AddNewTest()
        {
            using (System.Data.Entity.Core.EntityClient.EntityConnection entity = new System.Data.Entity.Core.EntityClient.EntityConnection("MyProjectEF1"))
            {
                entity.Open();
                EntityCommand cmd = entity.CreateCommand();
                cmd.CommandText = @"select doubt d from uLibrary as d where d.";
            }



            MyProjectEF mp = new MyProjectEF();



            mp.uLibrary.ToList();

            mp.uUsers.Add(new uUser()
            {
                UserName     = "******",
                Password     = Base64Helper.Base64Encode("msc@123321"),
                Email        = "*****@*****.**",
                CreationDate = DateTime.Now,
                EditDate     = DateTime.Now,
                FirstName    = "Edwin",
                LastName     = "Nie",
                FullName     = "Edwin Nie",
                LCV          = false
            });
            mp.SaveChanges();
        }
        public void DependencyResolver_used_to_resolve_DbProviderServices()
        {
            const string query = @"
SELECT VALUE p 
FROM CodeFirstContainer.Products AS p
WHERE p.ID > 3";

            var mockResolver = new Mock<IDbDependencyResolver>();
            mockResolver
                .Setup(
                    r => r.GetService(
                        It.Is<Type>(t => t == typeof(DbProviderServices)),
                        It.Is<string>(s => s == "System.Data.SqlClient")))
                .Returns(SqlProviderServices.Instance);

            using (var connection = new EntityConnection(SimpleModelEntityConnectionString))
            {
                connection.Open();

                new EntityCommand(query, connection, mockResolver.Object)
                    .ExecuteReader(CommandBehavior.SequentialAccess);
            }

            mockResolver.Verify(m => m.GetService(typeof(DbProviderServices), "System.Data.SqlClient"), Times.Once());
        }
 private EntityConnection GetEntityConnection()
 {
   string connectionString = String.Format(
       "metadata=TestDB.csdl|TestDB.msl|TestDB.ssdl;provider=MySql.Data.MySqlClient; provider connection string=\"{0}\"", GetConnectionString(true));
   EntityConnection connection = new EntityConnection(connectionString);
   return connection;
 }
        internal EntityTransaction(EntityConnection connection, DbTransaction storeTransaction)
        {
            DebugCheck.NotNull(connection);
            DebugCheck.NotNull(storeTransaction);

            _connection = connection;
            _storeTransaction = storeTransaction;
        }
        internal EntityTransaction(EntityConnection connection, DbTransaction storeTransaction)
        {
            Contract.Requires(connection != null);
            Contract.Requires(storeTransaction != null);

            _connection = connection;
            _storeTransaction = storeTransaction;
        }
        public void Verify_that_opening_connection_does_not_create_new_MetadataWorkspace()
        {
            var connection = new EntityConnection(connectionString);
            var workspace = connection.GetMetadataWorkspace();

            connection.Open();
            Assert.Same(workspace, connection.GetMetadataWorkspace());
        }
Exemple #12
0
        public EntityConnectionX()
        {
            EntityConnection connection = new EntityConnection("name=NorthwindEntities");

            // Open the connection.
            connection.Open();
            this.Connection = connection;
        }
 internal virtual EntityStoreSchemaGeneratorDatabaseSchemaLoader CreateDbSchemaLoader(
     EntityConnection connection, Version storeSchemaModelVersion)
 {
     return
         new EntityStoreSchemaGeneratorDatabaseSchemaLoader(
             connection,
             storeSchemaModelVersion);
 }
        public void Verify_that_metadata_is_the_same_for_two_workspaces_created_from_two_entity_connections_with_same_connection_strings()
        {
            var connection1 = new EntityConnection(connectionString);
            var connection2 = new EntityConnection(connectionString);
            var workspace1 = connection1.GetMetadataWorkspace();
            var workspace2 = connection2.GetMetadataWorkspace();

            Assert.Same(workspace1.GetItemCollection(DataSpace.CSpace), workspace2.GetItemCollection(DataSpace.CSpace));
            Assert.Same(workspace1.GetItemCollection(DataSpace.SSpace), workspace2.GetItemCollection(DataSpace.SSpace));
            Assert.Same(workspace1.GetItemCollection(DataSpace.CSSpace), workspace2.GetItemCollection(DataSpace.CSSpace));
        }
        public virtual EntityConnectionProxy CreateNew(DbConnection storeConnection)
        {
            var clonedConnection = new EntityConnection(_entityConnection.GetMetadataWorkspace(), storeConnection);

            var currentTransaction = _entityConnection.CurrentTransaction;
            if (currentTransaction != null
                && DbInterception.Dispatch.Transaction.GetConnection(
                    currentTransaction.StoreTransaction, _entityConnection.InterceptionContext) == storeConnection)
            {
                clonedConnection.UseStoreTransaction(currentTransaction.StoreTransaction);
            }

            return new EntityConnectionProxy(clonedConnection);
        }
 private void ejemploentity() {
     using (EntityConnection conn = new EntityConnection("name=travelEntitiesGeneral"))
     {
         conn.Open();
         EntityCommand cmd = conn.CreateCommand();
         cmd.CommandText = @"select c.BlogID from travelEntitiesGeneral.Blogs as c where c.BlogPosts.Count > 0";
         EntityDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
         while (reader.Read())
         {
             Console.WriteLine("BlogID = {0}", reader["BlogID"]);
         }
         conn.Close();
     }
 }
            Verify_that_conceptual_metadata_is_the_same_for_two_workspaces_created_from_two_entity_connections_with_reordered_metadata_in_connection_strings
            ()
        {
            var connectionString2 = string.Format(
                 @"metadata=res://EntityFramework.FunctionalTests.Transitional/System.Data.Entity.Metadata.MetadataCachingModel.msl|res://EntityFramework.FunctionalTests.Transitional/System.Data.Entity.Metadata.MetadataCachingModel.ssdl|res://EntityFramework.FunctionalTests.Transitional/System.Data.Entity.Metadata.MetadataCachingModel.csdl;provider=System.Data.SqlClient;provider connection string=""{0}""",
                ModelHelpers.SimpleConnectionString("tempdb"));

            var connection1 = new EntityConnection(connectionString);
            var connection2 = new EntityConnection(connectionString2);
            var workspace1 = connection1.GetMetadataWorkspace();
            var workspace2 = connection2.GetMetadataWorkspace();

            Assert.Same(workspace1.GetItemCollection(DataSpace.CSpace), workspace2.GetItemCollection(DataSpace.CSpace));
        }
Exemple #18
0
 static void Main(string[] args)
 {
     string city = "London";
     using (EntityConnection cn = new EntityConnection("Name=Entities"))
     {
         cn.Open();
         EntityCommand cmd = cn.CreateCommand();
         cmd.CommandText = @"SELECT VALUE c FROM Entities.Customers AS c WHERE
              c.Address.City = @city";
         cmd.Parameters.AddWithValue("city", city);
         DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
         while (rdr.Read())
             Console.WriteLine(rdr["CompanyName"].ToString());
         rdr.Close();
     }
 }
        public static bool insertDataToTable1(SqlConnection connection, System.Data.SqlClient.SqlTransaction transaction, int numberID, string text)
        {
            bool response = false;

            MetadataWorkspace workspace = new MetadataWorkspace
                (
                    new string[]
                    {
                        string.Format("res://{0}/MyTestDB.csdl" , "*"),
                        string.Format("res://{0}/MyTestDB.ssdl" , "*"),
                        string.Format("res://{0}/MyTestDB.msl" , "*")
                    },
                    new Assembly[]
                    {
                        Assembly.GetAssembly(typeof (jfso.demos.SqlTransaction.DAL.MyTestDV))
                    }
                );

            EntityConnection _conn = new EntityConnection(workspace, connection);

            try
            {
                using (var ctx = new MyTestDV(_conn, false))
                {

                    ctx.Database.UseTransaction(transaction);

                    ctx.TestTable1.Add(
                        new TestTable1()
                        {
                            ID = numberID,
                            Text = text
                        });


                    ctx.SaveChanges();

                    response = true;
                }
            }
            catch (Exception)
            {
                response = false;
            }

            return response;
        }
        static void Main(string[] args)
        {

            using (var ts = new TransactionScope())
            {

                EntityConnection cn = new EntityConnection("name=ASIEntities7");
                using (var ctx = new ASIEntities7(cn))
                {
                    // em alternativa a usar o Sql Server Profiler, pode fazer:
                    ctx.Database.Log = Console.Write;

                    //Em EF 5:
                    //((IObjectContextAdapter)ctx).ObjectContext.Connection.Open(); 
                    ctx.Database.Connection.Open();
                    var al = (from a in ctx.Alunos
                              where a.NumAl == 1111
                              select a)
                                .First();


                    al.Nome = "xico";


                   
                    using (var ctx1 = new ASIEntities7(cn))
                    {
					
					
					
                        //Em EF5:
                        //((IObjectContextAdapter)ctx1).ObjectContext.Connection.Open(); 
                        //ctx1.Database.Connection.Open();
                        var al1 = (from a in ctx.Alunos
                                   where a.NumAl == 4444
                                   select a)
                                .First();
                        al1.Nome = "xxxx";
						ctx1.SaveChanges();
                    }

                    ctx.SaveChanges();
                }
// ponto 1: observar no Sql Server Profiler
                ts.Complete();
            }
        }
Exemple #21
0
        public SGCoopSTEntities()
            : base("name=SGCoopSTEntities")
        {
            string providerName = "System.Data.SqlClient";
            string serverName = "10.10.11.115";
            string databaseName = "SGCoopST";
            string password="******";
            string userid = "sa";
            // Initialize the connection string builder for the
            // underlying provider.
            SqlConnectionStringBuilder sqlBuilder =
                new SqlConnectionStringBuilder();

            // Set the properties for the data source.
            sqlBuilder.DataSource = serverName;
            sqlBuilder.InitialCatalog = databaseName;
            sqlBuilder.IntegratedSecurity = false;
            sqlBuilder.Password = password;
            sqlBuilder.UserID = userid;

            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder =
                new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = providerName;

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/GOLDMEM.Entity.GMModel.csdl
                                                    |res://*/GOLDMEM.Entity.GMModel.ssdl
                                                    |res://*/GOLDMEM.Entity.GMModel.msl";
            EntityConnection enCon = new EntityConnection(entityBuilder.ToString());
            if (enCon.State== System.Data.ConnectionState.Closed)
            {
                enCon.Open();
            }
        }
        public void When_Same_Primary_Key_Name_Is_Used_For_Two_Tables_Correct_Number_Of_MetaData_Rows_Is_Returned()
        {
            this.CreateIfNotExists();
            var workspace = CreateMetadataWorkspace();            
            var connection = new EntityConnection(workspace, new SqlCeConnection(dbConnectionString));
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = TableDetailSql;
            var rowCount = 0;

            using (var reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
            {
                while (reader.Read())
                {
                    rowCount++;
                }
            }

            Assert.Equal(4, rowCount);
        }
        void Temp()
        {
            #region EntityConnectionCreationAndUsage

            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder
            {
                Provider = "System.Data.SqlClient",
                ProviderConnectionString = "the database connection string",
                Metadata = @"res://*/MySample.csdl|res://*/MySample.ssdl|res://*/MySample.msl"
            };

            EntityConnection entityConn = new EntityConnection(entityBuilder.ToString());

            using (MySampleContainer ctx = new MySampleContainer(entityConn))
            {
                //use the DbContext as required
            }

            #endregion
        }
Exemple #24
0
            public void ExecutionStrategy_is_used_to_recover_from_a_transient_error()
            {
                var storeConnectionState = ConnectionState.Open;
                var transientExceptionThrown = false;
                var storeConnectionMock = new Mock<DbConnection>(MockBehavior.Strict);
                storeConnectionMock.Setup(m => m.Close()).Callback(() => storeConnectionState = ConnectionState.Closed);
                storeConnectionMock.Setup(m => m.Open()).Callback(() => storeConnectionState = ConnectionState.Open);
                storeConnectionMock.SetupGet(m => m.DataSource).Returns("fake");
                storeConnectionMock.SetupGet(m => m.State).Returns(() => storeConnectionState);
                storeConnectionMock.Protected().Setup<DbTransaction>("BeginDbTransaction", IsolationLevel.Unspecified)
                                   .Returns<IsolationLevel>(
                                       il =>
                                           {
                                               if (!transientExceptionThrown)
                                               {
                                                   transientExceptionThrown = true;
                                                   storeConnectionState = ConnectionState.Broken;
                                                   throw new TimeoutException();
                                               }
                                               return new Mock<DbTransaction>().Object;
                                           });

                var entityConnection = new EntityConnection(CreateMetadataWorkspaceMock().Object, storeConnectionMock.Object, true, true);

                var executionStrategyMock = new Mock<IDbExecutionStrategy>();
                executionStrategyMock.Setup(m => m.Execute(It.IsAny<Func<DbTransaction>>())).Returns<Func<DbTransaction>>(
                    a =>
                        {
                            storeConnectionMock.Protected()
                                               .Verify<DbTransaction>(
                                                   "BeginDbTransaction", Times.Never(), IsolationLevel.Unspecified);

                            Assert.Throws<TimeoutException>(() => a());

                            storeConnectionMock.Protected()
                                               .Verify<DbTransaction>(
                                                   "BeginDbTransaction", Times.Once(), IsolationLevel.Unspecified);

                            var result = a();

                            storeConnectionMock.Protected()
                                               .Verify<DbTransaction>(
                                                   "BeginDbTransaction", Times.Exactly(2), IsolationLevel.Unspecified);

                            return result;
                        });

                MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object));
                try
                {
                    entityConnection.BeginTransaction();
                }
                finally
                {
                    MutableResolver.ClearResolvers();
                }

                executionStrategyMock.Verify(m => m.Execute(It.IsAny<Func<DbTransaction>>()), Times.Once());
            }
Exemple #25
0
            public void EntityConnection_automatically_opened_if_underlying_StoreConnection_is_opened_with_ambient_txn()
            {
                using (new TransactionScope())
                {
                    var storeConnectionState = ConnectionState.Closed;
                    var storeConnectionMock = new Mock<DbConnection>(MockBehavior.Strict);
                    storeConnectionMock.Setup(m => m.OpenAsync(It.IsAny<CancellationToken>())).Callback(
                        () => storeConnectionState = ConnectionState.Open).Returns(Task.FromResult(1));
                    storeConnectionMock.Setup(m => m.Close()).Callback(() => storeConnectionState = ConnectionState.Closed);
                    storeConnectionMock.SetupGet(m => m.State).Returns(() => storeConnectionState);
                    storeConnectionMock.SetupGet(m => m.DataSource).Returns("fake");

                    var metadataWorkspaceMock = new Mock<MetadataWorkspace>(MockBehavior.Strict);
                    var entityConnection = new EntityConnection(metadataWorkspaceMock.Object, storeConnectionMock.Object, true, true);
                    Assert.Equal(ConnectionState.Closed, entityConnection.State); // entityConnection state
                    Assert.Equal(ConnectionState.Closed, entityConnection.StoreConnection.State); // underlying storeConnection state

                    // open underlying store connection without explicitly opening entityConnection
                    entityConnection.StoreConnection.OpenAsync().Wait();
                    storeConnectionMock.Raise(
                        conn => conn.StateChange += null, new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open));

                    Assert.Equal(ConnectionState.Open, entityConnection.State); // entityConnection state is automatically updated
                    Assert.Equal(ConnectionState.Open, entityConnection.StoreConnection.State);

                    // now close underlying store connection (without explicitly closing entityConnection)
                    entityConnection.StoreConnection.Close();
                    storeConnectionMock.Raise(
                        conn => conn.StateChange -= null, new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed));

                    Assert.Equal(ConnectionState.Closed, entityConnection.State);
                    Assert.Equal(ConnectionState.Closed, entityConnection.StoreConnection.State);
                }
            }
Exemple #26
0
            public void EntityConnection_automatically_closed_if_underlying_StoreConnection_is_closed_without_txn()
            {
                var storeConnectionState = ConnectionState.Closed;
                var storeConnectionMock = new Mock<DbConnection>(MockBehavior.Strict);
                storeConnectionMock.Setup(m => m.OpenAsync(It.IsAny<CancellationToken>())).Callback(
                    () => storeConnectionState = ConnectionState.Open).Returns(Task.FromResult(1));
                storeConnectionMock.Setup(m => m.Close()).Callback(() => storeConnectionState = ConnectionState.Closed);
                storeConnectionMock.SetupGet(m => m.State).Returns(() => storeConnectionState);
                storeConnectionMock.SetupGet(m => m.DataSource).Returns("fake");

                // open entityConnection - both entityConnection and store connection should now be open
                var entityConnection = new EntityConnection(CreateMetadataWorkspaceMock().Object, storeConnectionMock.Object, true, true);
                entityConnection.OpenAsync().Wait();
                storeConnectionMock.Raise(
                    conn => conn.StateChange += null, new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open));
                Assert.Equal(ConnectionState.Open, entityConnection.State); // entityConnection state
                Assert.Equal(ConnectionState.Open, entityConnection.StoreConnection.State); // underlying storeConnection state

                // now close the underlying store connection without explicitly closing entityConnection
                entityConnection.StoreConnection.Close();
                storeConnectionMock.Raise(
                    conn => conn.StateChange -= null, new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed));

                Assert.Equal(ConnectionState.Closed, entityConnection.State); // entityConnection state automatically updated
                Assert.Equal(ConnectionState.Closed, entityConnection.StoreConnection.State);

                // now re-open the store connection and EntityConnection is "resurrected" to an Open state
                entityConnection.StoreConnection.OpenAsync().Wait();
                storeConnectionMock.Raise(
                    conn => conn.StateChange += null, new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open));
                Assert.Equal(ConnectionState.Open, entityConnection.State);
                Assert.Equal(ConnectionState.Open, entityConnection.StoreConnection.State);
            }
Exemple #27
0
            public void ExecutionStrategy_is_used()
            {
                var storeConnectionState = ConnectionState.Closed;
                var storeConnectionMock = new Mock<DbConnection>(MockBehavior.Strict);
                storeConnectionMock.Setup(m => m.OpenAsync(It.IsAny<CancellationToken>())).Returns(
                    () =>
                        {
                            storeConnectionState =
                                ConnectionState.Open;

                            return Task.FromResult(true);
                        });
                storeConnectionMock.SetupGet(m => m.DataSource).Returns("fake");
                storeConnectionMock.SetupGet(m => m.State).Returns(() => storeConnectionState);

                var entityConnection = new EntityConnection(CreateMetadataWorkspaceMock().Object, storeConnectionMock.Object, true, true);

                var executionStrategyMock = new Mock<IDbExecutionStrategy>();
                executionStrategyMock.Setup(m => m.ExecuteAsync(It.IsAny<Func<Task>>(), It.IsAny<CancellationToken>()))
                                     .Returns<Func<Task>, CancellationToken>(
                                         (f, c) =>
                                             {
                                                 storeConnectionMock.Verify(m => m.OpenAsync(It.IsAny<CancellationToken>()), Times.Never());
                                                 f().Wait();
                                                 storeConnectionMock.Verify(m => m.OpenAsync(It.IsAny<CancellationToken>()), Times.Once());
                                                 return Task.FromResult(true);
                                             });

                MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object));
                try
                {
                    entityConnection.OpenAsync().Wait();
                }
                finally
                {
                    MutableResolver.ClearResolvers();
                }

                executionStrategyMock.Verify(m => m.ExecuteAsync(It.IsAny<Func<Task>>(), It.IsAny<CancellationToken>()), Times.Once());
            }
Exemple #28
0
            public void StoreConnection_state_mimics_EntityConnection_state_if_only_EntityConnection_is_used_without_txn()
            {
                var storeConnectionState = ConnectionState.Closed;
                var storeConnectionMock = new Mock<DbConnection>(MockBehavior.Strict);
                storeConnectionMock.Setup(m => m.OpenAsync(It.IsAny<CancellationToken>())).Callback(
                    () => storeConnectionState = ConnectionState.Open).Returns(Task.FromResult(1));
                storeConnectionMock.Setup(m => m.Close()).Callback(() => storeConnectionState = ConnectionState.Closed);
                storeConnectionMock.SetupGet(m => m.State).Returns(() => storeConnectionState);
                storeConnectionMock.SetupGet(m => m.DataSource).Returns("fake");

                var entityConnection = new EntityConnection(CreateMetadataWorkspaceMock().Object, storeConnectionMock.Object, true, true);
                Assert.Equal(ConnectionState.Closed, entityConnection.State); // entityConnection state
                Assert.Equal(ConnectionState.Closed, entityConnection.StoreConnection.State); // underlying storeConnection state

                // open entityConnection (automatically opens store connection)
                entityConnection.OpenAsync().Wait();
                storeConnectionMock.Raise(
                    conn => conn.StateChange += null, new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open));

                Assert.Equal(ConnectionState.Open, entityConnection.State); // entityConnection state
                Assert.Equal(ConnectionState.Open, entityConnection.StoreConnection.State); // underlying storeConnection state

                // close entityConnection without explicitly closing underlying store connection 
                entityConnection.Close();
                storeConnectionMock.Raise(
                    conn => conn.StateChange -= null, new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed));

                Assert.Equal(ConnectionState.Closed, entityConnection.State); // entityConnection state
                Assert.Equal(ConnectionState.Closed, entityConnection.StoreConnection.State); // underlying storeConnection state
            }
 // <summary>
 // Constructs a new EntityCommand given a EntityConnection and an EntityCommandDefition. This
 // constructor is used by ObjectQueryExecution plan to execute an ObjectQuery.
 // </summary>
 // <param name="connection"> The connection against which this EntityCommand should execute </param>
 // <param name="entityCommandDefinition"> The prepared command definition that can be executed using this EntityCommand </param>
 internal EntityCommand(
     EntityConnection connection, EntityCommandDefinition entityCommandDefinition, DbInterceptionContext context, EntityDataReaderFactory factory = null)
     : this(entityCommandDefinition, context, factory)
 {
     _connection = connection;
 }
Exemple #30
0
            public void Exceptions_from_Underlying_dbConnection_are_wrapped()
            {
                var dbConnectionState = ConnectionState.Closed;
                var dbConnectionMock = new Mock<DbConnection>(MockBehavior.Strict);
                dbConnectionMock.Setup(m => m.OpenAsync(It.IsAny<CancellationToken>())).Throws(
                    new AggregateException(new InvalidOperationException()));
                dbConnectionMock.SetupGet(m => m.State).Returns(() => dbConnectionState);
                dbConnectionMock.SetupGet(m => m.DataSource).Returns("fake");

                var entityConnection = new EntityConnection(CreateMetadataWorkspaceMock().Object, dbConnectionMock.Object, true, true);

                Assert.Equal(
                    Strings.EntityClient_ProviderSpecificError("Open"),
                    Assert.Throws<EntityException>(
                        () => ExceptionHelpers.UnwrapAggregateExceptions(
                            () => entityConnection.OpenAsync().Wait())).Message);

                dbConnectionMock.Verify(m => m.OpenAsync(It.IsAny<CancellationToken>()), Times.Once());
            }
 internal ObjectContextForMock(EntityConnection connection, IEntityAdapter entityAdapter = null)
     : base(null, null, null, entityAdapter)
 {
     _connection = connection;
 }
 /// <summary>
 /// Constructs the EntityCommand object with the given eSQL statement and the connection object to use
 /// </summary>
 /// <param name="statement"> The eSQL command text to execute </param>
 /// <param name="connection"> The connection object </param>
 /// <param name="resolver"> Resolver used to resolve DbProviderServices </param>
 public EntityCommand(string statement, EntityConnection connection, IDbDependencyResolver resolver)
     : this(statement, connection)
 {
     _dependencyResolver = resolver;
 }
 internal EntityCommand(string statement, EntityConnection connection, EntityDataReaderFactory factory)
     : this(statement, new DbInterceptionContext(), factory)
 {
     _connection = connection;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.EntityClient.EntityCommand" /> class with the specified statement, connection and transaction.
 /// </summary>
 /// <param name="statement">The text of the command.</param>
 /// <param name="connection">A connection to the data source.</param>
 /// <param name="transaction">The transaction in which the command executes.</param>
 public EntityCommand(string statement, EntityConnection connection, EntityTransaction transaction)
     : this(statement, connection, transaction, new EntityDataReaderFactory())
 {
 }
 internal EntityCommand(
     string statement, EntityConnection connection, EntityTransaction transaction, EntityDataReaderFactory factory)
     : this(statement, connection, factory)
 {
     _transaction = transaction;
 }
 public bool ConnectionOpening(EntityConnection connection, DbInterceptionContext interceptionContext)
 {
     return !interceptionContext.DbContexts.Contains(_context, ReferenceEquals);
 }
Exemple #37
0
 internal EntityCommand(string statement, EntityConnection connection, EntityDataReaderFactory factory)
     : this(statement, factory)
 {
     _connection = connection;
 }