user3401335
user3401335

Reputation: 2405

query with list of type

i have a list of type

List<Type> list = new List<Type>();
list.Add(typeof(class1))
list.Add(typeof(class2))

that contains a list of type that are nhibernate table. class1 is a sql table as class2.

now i want a query like

int num = 0;
foreach (var item in list)
{                
    num += session.Query<item>().Count();
}

session is the ISession class.

the problem is with item, 'because is a variable but is used like a type'

how can i convert the type to the class?

Upvotes: 0

Views: 58

Answers (1)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

You need to create the generic method via reflection:

int num = 0;
MethodInfo genericMethod = session.GetType().GetMethod("Query");
foreach (var item in list)
{   
    MethodInfo specificMethod = genericMethod.MakeGenericMethod(item);
    IQueryable result = (IQueryable)method.Invoke(session, new object[0]);
    num += result.Count();
}

This at first gets the MethodInfo for the generic Query method (maybe the name is not 100% correct, try it).
Then it creates a specifically typed MethodInfo by calling MakeGenericMethod with the current type in item.
This method can finally be invoked, and the returned object casted to your expected result type (I presumed that Query returns an IQueryable).

Upvotes: 1

Related Questions