2012-04-12 11 views
9

ho questo:NHibernate GetAll

public static class Domain 
{ 
    private const string sessionKey = "NHib.SessionKey"; 
    private static ISessionFactory sessionFactory; 

    public static ISession CurrentSession 
    { 
     get 
     { 
      return GetSession(true); 
     } 
    } 

    static Domain() 
    { 
    } 

    public static void Init() 
    { 
     sessionFactory = new Configuration().Configure("Nhibernate.cfg.xml").BuildSessionFactory(); 
    } 

    public static void Close() 
    { 
     ISession currentSession = GetSession(false); 

     if (currentSession != null) 
     { 
      currentSession.Close(); 
     } 
    } 

    private static ISession GetSession(bool getNewIfNotExists) 
    {    
     ISession currentSession; 

     if (HttpContext.Current != null) 
     { 
      HttpContext context = HttpContext.Current; 
      currentSession = context.Items[sessionKey] as ISession; 

      if (currentSession == null && getNewIfNotExists) 
      { 
       currentSession = sessionFactory.OpenSession(); 
       context.Items[sessionKey] = currentSession; 
      } 
     } 
     else 
     { 
      currentSession = CallContext.GetData(sessionKey) as ISession; 

      if (currentSession == null && getNewIfNotExists) 
      { 
       currentSession = sessionFactory.OpenSession(); 
       CallContext.SetData(sessionKey, currentSession); 
      } 
     } 

     return currentSession; 
    } 
} 
public class Question 
{ 
    public virtual int Id { get; protected set; } 

    public virtual string Text { get; set; } 

    public virtual string Answer1 { get; set; } 

    public virtual string Answer2 { get; set; } 

    public virtual string Answer3 { get; set; } 

    public virtual string Answer4 { get; set; } 

    public virtual int NumberOfRight { get; set; } 

    public override string ToString() 
    { 
     return this.Text; 
    } 
} 

e posso fare le operazioni CRUD con tutta la domanda nel database.
Ma ho bisogno di mostrare tutte le domande, come ottenerle?
nel mio database le domande hanno ID: 1,2,3,100. Non credo, che, attraverso tutte le possibili Id - è accettabile ...

risposta

20

È possibile utilizzare il metodo di estensione Query<T> dallo spazio dei nomi NHibernate.Linq oppure è possibile utilizzare ISession.QueryOver<T>:

var allQuestions = session.Query<Question>().ToList(); 
// or 
var allQuestions = session.QueryOver<Question>().List();