Skip to content

Quick start

Stelio Kontos edited this page Sep 25, 2023 · 9 revisions

Define your entities

public class Article
{
    public long Id { get; set; }
    public string Title { get; set; }
    public DateTime DateCreated { get; set; }
    public bool Draft { get; set; }
    public string Content { get; set; }
}

For more information about mapping entities, see mapping entities

Create an instance of PetaPoco

var db = new PetaPoco.Database("connectionStringName");

// Or the fluent configuration (PostgreSQL as an example)
var db = DatabaseConfiguration.Build()
         .UsingConnectionString("Host=127.0.0.1;Username=petapoco;Password=petapoco;Database=petapoco;Port=5001")
         .UsingProvider<PostgreSQLDatabaseProvider>()
         .UsingDefaultMapper<ConventionMapper>(m =>
         {
             m.InflectTableName = (inflector, s) => inflector.Pluralise(inflector.Underscore(s));
             m.InflectColumnName = (inflector, s) => inflector.Underscore(s);
         })
         .Create();

For more information about instantiating PetaPoco, see ways to instantiate PetaPoco

Save an entity

var article = new Article { Title = "Our first entry", DateCreated = DateTime.UtcNow(), Content = "Some content..." };

db.Save("Articles", "Id", article);
// With more advanced mapping, you could have called db.Save(article);

For more information about inserting, updating or saving entities, see inserting, updating, deleting and saving.

Query for all articles

foreach (var a in db.Query<article>("SELECT * FROM Articles"))
{
    Console.WriteLine($"{a.Id} - {a.Title}");
}

For more information about querying, see querying

Delete the article

db.Delete("Articles", "Id", article.Id);
// Or db.Delete("Articles", "Id", article);
// With more advanced mapping, you could have called db.Delete(article);