In this example we setup a data model for a simple product ordering system.

Here is the entity model:
    public interface IProduct
    {
        string Name { get; set; }
        int Price { get; set; }
    }

    public interface IOrder
    {
        DateTime Date { get; set; }
        IUser User { get; set; }
        IProduct Product { get; set; }
    }

    public interface IUser
    {
        string Username { get; set; }
        int Age { get; set; }
    }

    public interface IDataModel
    {
        ICollection<IUser> Users { get; set; }
        ICollection<IProduct> Products { get; set; }
        ICollection<IOrder> Orders { get; set; }
    }


Notice that we use ICollection to declare lists of items. This means we can use LINQ to query the collection.

Initialization of Context is similar to previous examples:
var file = new FileStream("data.dat", FileMode.OpenOrCreate);
var storage = new IndexedFileStorage(file, 256, true);
Context ctx = new Context(typeof(IDataModel), null , storage);

Creating data is same as plain objects, except that we use Workspace.New<>:
// Create 100 users
ws.Data.Users = ws.New<ICollection<IUser>>();
for (int i = 0; i < 100; i++)
{
  IUser usr = ws.New<IUser>();
  usr.Username = "User" + i;
  usr.Age = i;

  ws.Data.Users.Add(usr);
}


We use the same approach to create products and orders:
//Create 100 products
ws.Data.Products = ws.New<ICollection<IProduct>>();
for (int i = 0; i < 100; i++)
{
  IProduct prd = ws.New<IProduct>();
  prd.Name = "Product" + i;
  prd.Price = i;

  ws.Data.Products.Add(prd);
}

// Create 100 orders
ws.Data.Orders = ws.New<ICollection<IOrder>>();
for (int i = 0; i < 100; i++)
{
  // Use LINQ to find user with appropriate age
  var user = ws.Data.Users.Single(u => u.Age == i);

  // Use LINQ to find product with appropriate price
  var product = ws.Data.Products.Single(p => p.Price.Equals(i));

  var order = ws.New<IOrder>();
  order.Date = DateTime.UtcNow;
  order.Product = product;
  order.User = user;

  ws.Data.Orders.Add(order);
}


We use LINQ to query all orders made by users with age > 75:
Console.WriteLine("Date\tProduct\tUser\tPrice");
using (var ws = ctx.OpenWorkspace(IsolationLevel.ReadOnly))
{
  var orders = ws.Data.Orders.Where(o => o.User.Age > 75);
  foreach (var item in orders)
  {
    Console.WriteLine("{0}\t{1}\t{2}\t{3}", item.Date, item.Product.Name, item.User.Username, item.Product.Price);
  }
}


Finally, we dispose the file for clean shutdown:
storage.Dispose();


Full source code for this example can be found in Execom.IOG.ObjectDB project in project source code.

Last edited Mar 14, 2012 at 10:17 AM by nenadsabo, version 3

Comments

No comments yet.