Thursday, November 01, 2007

Table Lookup & ActiveRecord Type Hierarchy

In any database application I can say. We need to have a read-only list for user to pick instead of manually key in. I knew that this can be done easily using Castle.ActiveRecord so I started out like this:

Design a lookup table

"Lookup" Table Schema:
  • ID - int primary key
  • Name - varchar(50)
  • Type - Discreminator Column
Very simple.

Generate ActiveRecord classes
[ActiveRecord("List_Lookups",
DiscriminatorColumn = "Type",
DiscriminatorType = "String",
DiscriminatorValue = "NA")]
public class Lookup: ActiveRecordBase
{
.... some code ...
}

sub-class code like this
[ActiveRecord(DiscriminatorValue = "PTL")]
public class ProjectTypeList: Lookup
{
}
Testing
Lucky that I start with this:
ProjectTypeList.DeleteAll();
Which cause all the records in the Lookup table deleted. WEIRD !
It suppose to delete all records in Lookup table with column Type = "PTL"

Okay, I keep testing with FindAll() method and the result was not satisfied. I start lookup for the solution in the forum finally I got the answer from Hammett's replied.

The answer is:
"Implement our own DeleteAll(), FindAll() and other method by in the derived classes."

using Castle.ActiveRecord;

namespace PID.Net.Models
{
[ActiveRecord(DiscriminatorValue = "PTL")]
public class ProjectTypeList: Lookup
{
public new static void DeleteAll()
{
DeleteAll(typeof (ProjectTypeList));
}
public new static ProjectTypeList[] FindAll()
{
return (ProjectTypeList[]) FindAll(typeof (ProjectTypeList));
}
}
}

I hope I won't waste my time next time I tried to deal with this scenario.