Setting a database connection - activa/iridium GitHub Wiki

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");

Any database operation performed on a table needs a IDataSet, which is an immutable object. To get a dataset for a context, call the DataSet<T>() method:

var customer = dbContext.DataSet<Customer>().Read(1);

// To work with single objects, you don't actually need a DataSet<T>, but you can:

var customer = dbContext.Read<Customer>(1);
//
dbContext.Insert(customer);
//
dbContext.Delete(customer);

The dataset class is a zero weight object so there's no penalty in calling DataSet every time, but it's not very readable so it may be better to store the dataset objects for later use:

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:

###Deriving from StorageContext

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);

####Static context

If you prefer to have your context and datasets available as static fields, you can do something like this:

public static class DB
{
   public class MyContext : SqliteContext
   {
      public MyContext() : base("my.db") {}

      IDataSet<Customer> Customers;
      IDataSet<Order> Orders;
      IDataSet<Product> Products;
   }

   public static MyContext Context = new MyContext();
}

/// ...

public void Main()
{
    Console.WriteLine("We have {0} customers in the database",
                 DB.Context.Customers.Count()
              );
}
⚠️ **GitHub.com Fallback** ⚠️