Let’s say we have an application with the following (highly simplified) object model:-

As you can see we have a Customer and a Customer’s Orders which we wish to persist to the database using XPO. This will work perfectly with 10, 100, 1,000, 10,000 orders say; however, somewhere alone the orders of magnitude your database is going to start to struggle with the numbers of Customers and their Orders. You can scale up your database server of course, but there comes a time when even that will not help. When dealing with database scalability I like to use the sharding pattern. In this pattern a large database is broken up into ever smaller pieces and clients access the required piece or shard.
In the non scalable solution the following code would be used to serialize the object model:-
namespace XPOScalabilityExample {
class Program {
static void Main(string[] args) {
//GS - Explicitly set the datalayer
string conn = MSSqlConnectionProvider.GetConnectionString(
"(local)", "Customers");
XpoDefault.DataLayer = XpoDefault.GetDataLayer(
conn, AutoCreateOption.DatabaseAndSchema);
//GS - Create a Customer and an Order and persist them
using (UnitOfWork uow = new UnitOfWork())
{
Customer customer = new Customer(uow);
customer.Name = "Gary Short";
customer.Address = "The Adress";
Order order = new Order(uow);
order.OrderedItem = "A widget";
order.OrderedQuantity = 4;
order.Price = 342.29M;
customer.Orders.Add(order);
order.Customer = customer;
uow.CommitChanges();
}
}
}
}
To implement sharding, in the first instance, we will partition the database geographically, placing customers in either the north or the south. The code to persist the Customer now looks like the following:-
namespace XPOScalabilityExample {
class Program {
static void Main(string[] args) {
//GS - Explicitly set the datalayer
string conn = MSSqlConnectionProvider.GetConnectionString(
"(local)", "North");
XpoDefault.DataLayer = XpoDefault.GetDataLayer(
conn, AutoCreateOption.DatabaseAndSchema);
//GS - Create a Customer and an Order and persist them
using (UnitOfWork uow = new UnitOfWork())
{
Customer customer = new Customer(uow);
customer.Name = "Gary Short";
customer.Address = "The Adress";
Order order = new Order(uow);
order.OrderedItem = "A widget";
order.OrderedQuantity = 4;
order.Price = 342.29M;
customer.Orders.Add(order);
order.Customer = customer;
uow.CommitChanges();
}
}
}
}
For demonstration purposes I have simulated the switch between servers by switching between databases on the same server, but I’m sure you get the idea. To access Customers in the south you would replace the word “North” with the word “South” in the connection string. Now that you have the idea of sharding we will look at a more advanced example next time.