Skip to content

Ways to instantiate PetaPoco

Wade Baglin edited this page Dec 14, 2015 · 29 revisions

There are various way to construct a new instance PetaPoco with each trying to solve a particular use case.

The API, as it stands, is currently comprised of:

public Database()
public Database(IDbConnection connection)
public Database(string connectionString, string providerName = null)
public Database(string connectionString, DbProviderFactory factory)
public Database(string connectionStringName)
public Database(string connectionString, IProvider provider)

Each constructor option explained

public Database()

The parameterless constructor is a quick and easy way to create a new instance of PetaPoco. This constructor will use the first connection string it finds in the app/web configuration.

Sample postgre app/web configuration file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.data>
    <DbProviderFactories>
      <remove invariant="Npgsql"/>
      <add name="PostgreSQL Data Provider" invariant="Npgsql" description=".Net Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql"/>
    </DbProviderFactories>
  </system.data>
  <connectionStrings>
    <add name="postgres" connectionString="Host=127.0.0.1;Username=petapoco;Password=petapoco;Database=petapoco;Port=5001;Pooling=false" providerName="Npgsql"/>
  </connectionStrings>
</configuration>

public Database(IDbConnection connection)

The constructor which takes an instance of an existing connection is one of PetaPoco's more interesting and less known features. The why lies with the use case. It's not hard to imagine a situation where a project uses its own implementation of a DAL or a product like EF and has a need to easily access/manipulate data. In such a case, one can simply acquire a IDbConnection and construct an instance of PetaPoco for easy data access and manipulation.

Note: Please be aware that PetaPoco does not take ownership of the connection management when using this constructor, that responsibility to left to the caller.

public Database(string connectionString, string providerName = null)

With this constructor one simply provides a connection string and optional provider name. If no provider name is given, the default SQL Server provider is used.

Note: the casing of the provider name does not matter, as comparisons are invariant culture ignore case.

Valid provider names are:

Provider Accepted provider names
MySqlDatabaseProvider MySql
MySqlDatabaseProvider MySql
PostgreSQLDatabaseProvider Npgsql
SQLiteDatabaseProvider SQLite
SqlServerCEDatabaseProviders SqlServerCe, SqlCeConnection
OracleDatabaseProvider Oracle
SqlServerDatabaseProvider (Default) SqlServer, System.Data.SqlClient

public Database(string connectionStringName)

public Database(string connectionString, IProvider provider)