views:

144

answers:

0

I'm making a generic MVC viewer/editor for data objects I've designed, modeled after ActiveRecord.

The data objects are completely generic, they can have primary keys that are strings, ints, int16s, whatever the database uses (the persistence layer at this organization uses all sorts of datatypes for primary keys and I want this MVC "browser/editor" to handle them all).

Creating the Edit links in the Index view is easy:

Response.Write("<td>" + Html.ActionLink("Edit", "Edit", new { id = pkValue }) + "</td>");

The problem is on the other side, in the Edit action:

public ActionResult Edit(object id)

Anything other than a string throws an exception when I try to use id as the sole element of an array of parameters to a static "select" method invoked via reflection to retrieve a hydrated data object to edit from the database:

object[] parameters = { id };
list = (List<T>)select.Invoke(null, parameters);

I know the CLR type of the parameter, and I know the "real" type of object id. Am I supposed to use some kind of gnarly case statement to do the type conversion manually, or is there a trick I can use to do the type conversion using the type of the parameter?

Can/Should I overload the ActionResult Edit() to take int, int16, int32, etc?

What should I do here to ensure that no matter the "real" type of id, I can pass it into the database without an exception being thrown?

Here's what I've tried so far:

I made my generic controller take two type parameters, one for the data object and another for the primary key datatype:

public class CoreDataController<t,T> : Controller  where T:IDataObjectBase<T>

Then I tried this move:

id = (t)id;
object[] parameters = { id};

BZZZRT! "the specified cast is invalid". id is "2" and t is int?