Link Search Menu Expand Document

CRUD Actions


Table-specific instances of MightyOrm also support CRUD actions (insert, update, delete).

No additional set up is required, all these examples are self-contained and work just as they are. All these methods also have variants which accept any reasonable arrary or enumerable of items to update multiple rows.

Update

Simple update using dynamic types:

var db = new MightyOrm(connectionString, "Person",  "PersonID");
var p = db.Single(42); // get from Person table by primary key
p.LoyalCustomer = true;
db.Update(p);

Or in a strongly-typed version (similar changes could be applied to any of the examples on this page):

var db = new MightyOrm<Person>(connectionString, primaryKeys: "PersonID");
var p = db.Single(42);
p.LoyalCustomer = true;
db.Update(p);

Insert

Insert a new database row, specifying some (or all) column values from an anonymous object:

var db = new MightyOrm(connectionString, "Person",  "PersonID");
// This insert syntax from an anonymous object would work even on a strongly typed instance of MightyOrm
db.Insert(new { GivenName = "Mike", FamilyName = "Beaton" });

Insert a new dynamic object:

var db = new MightyOrm(connectionString, "Person",  "PersonID");

// The new dynamic object will have fields for all columns which exist in the underlying table;
// it will additionally respect database column default values, if any are specified
var p = db.New();

p.GivenName = 'Mike';
p.FamilyName = 'Beaton';

db.Insert(p);

// The new primary key has been populated
Console.WriteLine(p.PersonID);

Column defaults (which are typically either constants or well known simple functions) are read from the table meta-data once, when first required, and then the column default values which New produces are generated by Mighty itself from that data, without any additional database access.

Delete

Delete a single item by primary key:

var db = new MightyOrm(connectionString, "Person",  "PersonID");
db.Delete(42);

Or delete one or more rows using a WHERE specification:

var db = new MightyOrm(connectionString, "Person",  "PersonID");
db.Delete("FamilyName = @0", "Smith");
// Or db.Delete(new { FamilyName = "Smith"}) if you prefer

Save

Save inserts if the item is new (i.e. has missing or default-only values for the primary key(s)), or updates the item otherwise:

var db = new MightyOrm(connectionString, "Person",  "PersonID");

var p = db.New();
p.GivenName = 'Mike';
p.FamilyName = 'Beaton';

// New item, Save does an insert
// The insert populates the primary key
db.Save(p);

p.LoyalCustomer = true;
// Item with primary key value, Save does an update
db.Save(p);