Geeks With Blogs

Scott Kuhl Warning: I may have no idea what I am talking about!

It is possible to load data at the object level using one of three overloaded Load methods by passing in either a DataRow, DataTable or IDataReader.  But you are more likely to use the static FetchByID method or an overloaded constructor.


FetchByID takes has one parameter, the primary key value of the object in GUID, integer or string format, and returns a populated object.

Product product = Product.FetchByID(id);

If the object is not found, SubSonic will not throw an error.  Instead you should check to see if the key property matches the passed in ID to determine if the object was found.

int id = 1;
Product product = Product.FetchByID(id);
if (product.ProductID == id)
    // Success
    // Not Found


To do the same thing using the overloaded constructor method that takes the primary key looks like this.

Product product = new Product(id);

By using another overloaded constructor that takes a column name and value as the parameters, it is possible to load the object based on another uniquely identifying column instead of the primary key.

Product product = new Product(Product.Columns.ProductName, "Chai");

Be careful when using the last form.  If you use a column that does not have a unique constraint and more than one record is returned by the database, your object will be populated with the first one.

Loading and Saving State

There is one other way to load an object.  Each object has a method called NewFromXML which creates an object from an XML string.  This method is meant to be used with the ToXML method to write the object's state to a temporary location such as Session state.

Session["Product"] = product.ToXML();
product = (Product)product.NewFromXML(Session["Product"].ToString());

Find the entire series of posts here.

Posted on Tuesday, November 28, 2006 2:28 PM SubSonic | Back to top

Comments on this post: Getting Started with SubSonic - Part 8, Classes - Retrieving a Single Object

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Scott Kuhl | Powered by: