0

What I have:

session.Query<Symptom>().First();

What I am trying to do:

var className="Symptom"
session.Query<className>().First()

Is it possible to do this in some way? If yes where to look because I've tried with Type.GetType etc, without success. And secondary question, I have to send via web request "type" that will be in that query syntax am I looking in good way? Or I am missing some point where I can just send somehow type from front-end to service and get data from database what I want. I am using that query to get data from Nhibernate, and I did not want to hardcode all possibile types that would come with request data.

EDIT:

When I try GetType I get:

cannot apply operator '<' to operands of type 'method group' and 'system.type'
Sebastian 506563
  • 6,980
  • 3
  • 31
  • 56

1 Answers1

3

Generic parameters are compile type construct. In your case you specify a string (runtine entity) as a type name, so you need to create a closed generic method instance at runtime via reflection.

Next code demonstrates this:

Suppose I have:

public void Query<T>()
{
    Console.WriteLine("Called Query with type: {0}", typeof(T).Name);
}

Now in order to call it with some type, I need to create a method instance with that type:

//type you need to create generic version with
var type = GetType().Assembly //assumes it is located in current assembly
                    .GetTypes()
                    .Single(t => t.Name == "MyType");

//creating a closed generic method
var method = GetType().GetMethod("Query")
                      .GetGenericMethodDefinition()
                      .MakeGenericMethod(type);

//calling it on this object
method.Invoke(this, null); //will print "Called Query with type: MyType"

Here is the full code on ideone.

Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90