views:

12

answers:

1

I would like to construct a dynamic Subsonic 3 query using code to get a collection of a type. The SQL would like this:

select * from @tableName where @columnName1 = @columnValue1

The subsonic query would look like this:

List<object> = new DB.Select.From<getTypeClass(tableName)>.Where(columnName1).IsEqualTo(columnValue1).ExecuteTypeList<getTypeClass(tableName)>();

I would like to accomplish this using reflection but I don't think it would be possible to put a non static item between the <> clauses.

A: 

The solution is to generate generic methods for the methods on the Select class and to be able to initiate a generic list of the same type.

Type toType;
var GenericListOfType = typeof(List<>).MakeGenericType(new []{toType});
var ListOfType = Activator.CreateInstance(GenericListOfType);

MethodInfo GenericExecuteTypedList = typeof(Select).GetMethod("ExecuteTypedList").MakeGenericMethod(toType);

And invoke this method like this:

ListOfType = GenericExecuteTypedList.Invoke(new Select().From(toType.Name), null);

The From method has an overload that accepts a string value. Passing the type name worked fine, in my case the table and class name were identical.

It is easy to add some where statements just before invoking the generic method.

jhoefnagels