[SubSonic] LoadFromPost method maps controls to object properties

Since SubSonic data access code and cuts way down on the repetitive grunt work, I've started to resent having to write any code at all. On a recent project, we found that since we weren't writing much data access or map related objects, the majority of the code we had to write revolved around shuttling data between controls and object properties.

You know, code like this:

int productQuantity = 0;
if (int.TryParse(txtproductQuantity.Text.Trim(), out productQuantity))
    this.Product.Quantity = productQuantity; 

Binding code is easy enough, but save "unbinding" code is a bit of a pain. I talked to Rob about how to make that easier - maybe a SubSonic textbox with an attribute which would map it back to a SubSonic object and automatically handle the bind / unbind code. Rob told me about a feature I hadn't noticed before - LoadFromPost().

All SubSonic ActiveRecord objects inherit a LoadFromPost() method, as in: Product.LoadFromPost()

LoadFromPost finds all the controls with the same name as the "Product" column names and initializes the object from them. It handles type checks, the ASP.NET nested control names like DataGrid1__ctl3_TextBox1, etc.

I noticed that the developers on this project who were new to SubSonic assumed they needed to use the query object to load a specific object from the database. The simplest method is to use the constructor overloads.

If you're loading by ID, you can just pass the ID in the constructor:

Product p = new Product(productId);

If you're looking it up by another column, you can specify the column name and value:

Product p = new Product(Product.Columns.ProductName, "Space Suit");

Keep in mind that the second constructor loads the first product WHERE ProductName = 'Space Suit'.

18 Comments

Comments have been disabled for this content.