0

How can I use a variable as type for calling an NHibernate query? My code looks (simplyfied) like this:

public string MyFunction()
{
    var myVar = typeof(MyModel);
    var myVar2 = ExecQuery<myVar>();
}

private List<T> ExecQuery<T>()
{
    var result = sessionService.GetDefaultSession()
         .Query<T>()
         .ToList();

    return result;
}

MyModel looks as follows:

public class MyModel
{
    public virtual int Id {get; set;}
    public virtual string Name {get; set;}
}

And the mapping:

public class MyModelMapping : ClassMapping<MyModel>
{
    public MyModelMapping()
    {
        Id(a => a.Id, b => b.Generator(Generators.Identity));

        Property(a => a.Name, b =>
        {
            b.NotNullable(true);
        });
    }
}

I get the error: myVar is a variable but is used like a type.

Any ideas? Thanks:)

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • In case you're actually trying to call `ExecQuery` with the type only known at runtime, check out this answer https://stackoverflow.com/questions/325156/calling-generic-method-with-a-type-argument-known-only-at-execution-time – Barry O'Kane Aug 29 '18 at 09:06

1 Answers1

0

Try to pass the type like this

public string MyFunction()
{
    var myVar2 = ExecQuery<MyModel>();
}
Antoine V
  • 6,998
  • 2
  • 11
  • 34
  • Thank you! I know about that way, but under my conditions it has to be the variable to be given as `ExecQuery` –  Aug 29 '18 at 09:11
  • so, that means it's possible duplicate of https://stackoverflow.com/questions/302577/how-to-use-typeof-or-gettype-as-generics-template – Antoine V Aug 29 '18 at 09:21
  • @Thiery V could possibly be, but I don't get how I can solve this now...can u help me maybe? –  Aug 29 '18 at 10:40