stuart-d2
5/11/2015 - 6:26 PM

Simple SQL Connection Object

Simple SQL Connection Object

 //Connection to A SQL Database : IDbConnection

//A. Object Declaration
public static IDbConnection BuildConnection() {
      var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TycheDB"].ConnectionString);
      connection.Open();
      return connection;
    }

***

//B.  App.config settings.. Ensure the proper connection strings are implemented.  

  <connectionStrings>
<add name="LocalDB" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;MultipleActiveResultSets=True" />
<add name="TycheDB" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TycheDB;Integrated Security=True;MultipleActiveResultSets=True" />
  </connectionStrings>

//C. Declared Elsewhere.  Typically in a 'Using' statement since it is system resource :
[...]
using (var connection = UtilityHelpers.BuildConnection()) {
        var messages = connection.Query(@"SELECT * FROM user_notification WHERE notification_id =            @notificationId", new { notificationId }).ToList();
        Assert.Equal(1, messages.Count());
        var then = DateTime.Now.AddMinutes(-1);
        Assert.True(messages.Single().deleted_on > then);
        connection.Close();
      }
    }