Skip to content

Active Record

Max Stepanskiy edited this page Mar 31, 2021 · 9 revisions

Here is the step-by-step example of Active Record Pattern implementation with Nemo. Although all CUD methods are not part of the objects they are available as extension methods and assume a match between an entity and a data row.

Step 1: Configure Nemo

ConfigurationFactory.Configure()
                .SetGenerateDeleteSql(true)
                .SetGenerateUpdateSql(true)
                .SetGenerateInsertSql(true);

Step 2: Define Entities

[Table("Customers")]
public class Customer
{
     [MapColumn("CustomerID"), PrimaryKey]
     public string Id { get; set; }
     [MapColumn("CustomerName")]
     public string Name { get; set; }
     public List<Order> Orders get; set; }
}

[Table("Orders")]
public class Order
{
     [MapColumn("OrderID"), PrimaryKey]
     public int Id { get; set; }
     [MapColumn("CustomerID"), References(typeof(Customer))]
     public string CustomerId { get; set; }
     public string ShipPostalCode { get; set; }
}

Step 3: Retrieve Objects

var customer = ObjectFactory.Retrieve<Customer, Order>(
                                     sql: @"select * from Customers where CustomerID = @CustomerID; 
                                            select * from Orders where CustomerID = @CustomerID",
                                     parameters: new ParamList { CustomerId => "ALFKI" }).FirstOrDefault();

Step 4: Modify Objects

customer.Delete() // Delete a customer

/* OR */

customer.Name += " Inc.";
customer.Update(); // Update a customer

/* OR */

// Unit of work allows to track an instance and apply updates in batch
using (ObjectScope.New(customer, autoCommit: false))
{
     customer.Name += " Inc.";
     customer.Orders[0].ShipPostalCode = "11111";
     customer.Orders.RemoveAt(1);

     var o = new Order();
     o.CustomerId = customer.Id;
     o.ShipPostalCode = "22222";
     customer.Orders.Add(o);

     // Access previous state of the customer
     Assert.AreNotEqual(customer.Old().Name, customer.Name);

     //customer.Rollback();
     customer.Commit();
}