In general, all database operations are performed on a StorageContext
object. A StorageContext object needs a DataProvider which is specific to the type of database you're using.
var dbContext = new StorageContext(new SqliteDataProvider("my.db")); // store dbContext somewhere
All database providers also have a dedicated Context class that you can use:
var dbContext = new SqliteContext("my.db");
In general, any database operation performed on a table needs to go through dataset (IDataSet<T>
), which is an immutable object. To get a dataset for a context, call the DataSet<T>()
method, where T
is the type of the object:
var customer = dbContext.DataSet<Customer>().Read(1);
To work with single objects, you don't actually need a DataSet
var customer = dbContext.Read<Customer>(1); // dbContext.Insert(customer); // dbContext.Delete(customer);
A dataset is a zero weight immutable object so there's no penalty in calling DataSet
var dbCustomers = dbContext.DataSet<Customer>(); var dbOrders = dbContext.DataSet<Order>(); var dbProducts = dbContext.DataSet<Product>(); // You can use those datasets many times as they are immutable: dbCustomers.Insert(new Customer { ... }); var someCustomers = dbCustomers.Where(...);
But there's a better way:
You can derive your own context class from StorageContext and let Iridium create all the datasets for you:
public class MyContext : SqliteContext { public MyContext() : base("my.db") {} IDataSet<Customer> Customers; // will be assigned automatically IDataSet<Order> Orders; // will be assigned automatically IDataSet<Product> Products; // will be assigned automatically }
var db = new MyContext(); var customer = db.Customers.Read(1);
If you prefer to have your context and datasets available as static fields, you can do something like this:
public static class App { public class MyDBContext : SqliteContext { public MyContext() : base("my.db") {} IDataSet<Customer> Customers; IDataSet<Order> Orders; IDataSet<Product> Products; } public static MyContext DB = new MyDBContext(); }
public void Main() { Console.WriteLine("We have {0} customers in the database", App.DB.Customers.Count() ); }