-
Notifications
You must be signed in to change notification settings - Fork 600
Support for dynamic
This is adapted the from the original documentation from toptensoftware.com/petapoco, crawled by the Wayback Machine on 8/3/2017.
PetaPoco's main focus is obviously to work with POCO objects. Sometimes though you just want to run query and not have to worry about declaring an object for results. C#'s dynamic support is perfect for this.
PetaPoco was originally inspired by Massive - which returns everything through dynamic Expando objects. For most uses I find this cumbersome and prefer strongly typed classes. There are cases however where support for dynamics is useful - particularly for joins, group by and other calculated queries.
To do a "dynamic" query just use the existing query methods but pass dynamic
as the generic parameter. The returned objects will have a property for each column returned by the query:
foreach (var a in db.Fetch<dynamic>("SELECT * FROM articles"))
{
Console.WriteLine($"{a.article_id} - {a.title}");
}
Note there's no support for automatic SELECT
clauses - since PetaPoco doesn't know the table name.
You can also do updates, inserts and deletes but you need to specify the table name and primary key of the table to update:
// Create a new record
dynamic a = new ExpandoObject();
a.title = "My New Article";
// Insert it
db.Insert("articles", "article_id", a);
// New record ID returned with a new property matching the primary key name
Console.WriteLine($"New record {a.article_id} inserted");
Here's an update:
// Update
var a = db.Single("SELECT * FROM articles WHERE article_id=@0", id);
a.title="New Title";
db.Update("articles", "article_id", a);
Delete()
, Save()
and IsNew()
all work similarly.
PetaPoco is proudly maintained by the Collaborating Platypus group and originally the brainchild of Brad Robinson