How to get object from session with unknown type a

2019-08-07 00:51发布

What I'm trying to do is get object data from session.

Code below should make clear all:

//Type of object which i need to get in runtime
Type someUnknownType = typeof(someObject);
int id = 1; // for example
// here i got error cannot resolved someUnknownType
ISession.Get<someUnknownType>(id);

How can I do that?

Edit: someObject is instance variable.

2条回答
Bombasti
2楼-- · 2019-08-07 01:04

You need to use this Get method:

ISession.Get(Type, Object);

Here is an example from the NHibernate documentation:

Cat cat = (Cat) sess.Get(catInstance.GetType(), id);
查看更多
不美不萌又怎样
3楼-- · 2019-08-07 01:16

First, you have a mistake:

  • if someObject is an instance variable, you can't call typeof(someObject). You can only call someObject.GetType()
  • if it is a type, you still use the generic version.

Have you tried to use non-generic version:

object x = ISession.Get(someObject.GetType(), id);
查看更多
登录 后发表回答