Once you’ve set up your connection strings in your configuration file (or not), the first action to have your code take is to open your data store. You can use one of four methods to do this.
Tries to open a connection to a data store using the connection string named Simple.Data.Properties.Settings.DefaultConnectionString
in your configuration file
var defaultDb = Database.Open(); var artist = defaultDb.Artists.FindByName("Aerosmith"); Console.WriteLine("Id: {0}, Name: {1}", artist.ArtistId, artist.Name);
Tries to open a connection to a data store using the connection string with the given connectionName
in your configuration file
var namedDb = Database.OpenNamedConnection("MvcMusicStoreDb"); var artist2 = namedDb.Artists.FindByName("Metallica"); Console.WriteLine("Id: {0}, Name: {1}", artist2.ArtistId, artist2.Name);
Tries to open a connection to a data store with the given literal connectionString
.
var magicDb = Database.OpenConnection("--Your Connection String--"); var artist3 = magicDb.Artists.FindByName("Iron Maiden"); Console.WriteLine("Id: {0}, Name: {1}", artist3.ArtistId, artist3.Name);
OpenConnection
has a second variant that allows you to specify the name of the Simple.Data provider that should be used to open the connection. If you’ve only one provider in your project, Simple.Data will pick it up by default. If you’d like to identify it explicitly or need to switch between two providers in you project, you’ll need to use this.
var magicDb = Database.OpenConnection("--Your Connection String--", "providerString"); var artist3 = magicDb.Artists.FindByName("Iron Maiden"); Console.WriteLine("Id: {0}, Name: {1}", artist3.ArtistId, artist3.Name);
In the code above, providerString
can be one of the following values:
Provider | String To Use |
---|---|
Simple.Data.SqlServer | System.Data.SqlServer |
Simple.Data.SqlCe35 | sdf |
Simple.Data.SqlCe40 | System.Data.SqlServerCe System.Data.SqlServerCe.4.0 |
Simple.Data.MySql | MySql.Data.MySqlClient |
Simple.Data.Oracle | Oracle.DataAccess.Client Devart.Data.Oracle |
Simple.Data.Sqlite | db sqlite |
Simple.Data.SqlAnywhere | iAnywhere.Data.SqlAnywhere |
Simple.Data.PostgreSql | Npgsql |
Simple.Data.Access | mdb accdb System.Data.OleDb |
Tries to open a connection to a data store with the given filepath
.
var fileDb = Database.OpenConnection("MvcMusicStore.sdf"); var artist4 = fileDb.Artists.FindByName("Alanis Morrisette"); Console.WriteLine("Id: {0}, Name: {1}", artist4.ArtistId, artist4.Name);
Simple.Data is quite aggressive in closing connections and holds no open connections to a data store by default, so you can keep the Database
object returned from the Open*()
methods hanging around without worrying.