Decoupled Code using SubSonic

Subsonic is fantastic when generating a bunch of classes directly from the database structure…but the issue comes when OO/Application Objects clash with relational database structures.   An idea is to use Subsonic to query the data from the database and map the data directly to a application/OO object.

A really good example following the link below is to have a Product class that has a various number of attributes.  When you query data from the database using Subsonic you can do the following:

return Northwind.DB.Select("ProductID", "ProductName", "UnitPrice")
                .From<Northwind.Product>().ExecuteTypedList<Product>();

//where Product is a Application Object.

This attempts to map the data to ProductID, ProductName and UnitPrice attributes in the Product object.

Another example is to create a new application object that inherits from your subsonic generated class.
This is really handy if you want to extend and add custom business logic.

[Serializable]
public class PersonObj : Person //Person is the SubSonic generated class
{
    public void ResetSubscription()
    {
        SubscriptionDate = DateTime.Now; //Call the SubscriptionDate database field
        ExpiryDate = DateTime.Now.AddYears(1);
        Save(); //Commit the changes back to the database
    }
}

return Select()
                .From<Person>().ExecuteSingle<PersonObj>().ResetSubscription(); //Notice the PersonObj on the end

References:

http://subsonicproject.com/2-1-pakala/subsonic-writing-decoupled-testable-code-with-subsonic-2-1/

This entry was posted in C#, Open Source and tagged . Bookmark the permalink.