سؤال

I am using following code to setup connection string:

ConfigurationSourceBuilder builder = new ConfigurationSourceBuilder ();
            builder.ConfigureData ()
                   .ForDatabaseNamed ( "TestDatabase" )
                     .ThatIs.ASqlDatabase ()
                     .WithConnectionString ( "Data Source=127.0.0.1;User Id=sa;Password=123;Initial Catalog=DataAccessExamples;" )
                     .AsDefault ();

            var configSource = new DictionaryConfigurationSource ();
            builder.UpdateConfigurationWithReplace ( configSource );
            EnterpriseLibraryContainer.Current
              = EnterpriseLibraryContainer.CreateDefaultContainer ( configSource );

After executing above code I expect following code to work but it says connection not initialized and command.Connection property always keeps null.

Database database = DatabaseFactory.CreateDatabase ();
            DbCommand command = database.GetSqlStringCommand ( "Select * from TT" );

            DbDataReader dbReader = command.ExecuteReader ( System.Data.CommandBehavior.CloseConnection );

            while (dbReader.Read ())
            {
                System.Diagnostics.Debug.WriteLine ( dbReader[0].ToString () );
            }

Please can anyone tell me why connection is not getting initialized?

I am using above code in a library project and want to configure DAAB at runtime.

Thanks

هل كانت مفيدة؟

المحلول

For one, why are you hard coding the connection string? Wouldn't it make more sense to have the connection string in the config file for your application?

Why do you need to use the Database factory?

        SqlDatabase db = new SqlDatabase("some connection string from the config");
        DbCommand cmd = db.GetSqlStringCommand(sqlStatement);
        IDataReader reader = db.ExecuteReader(cmd);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top