Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate GetAll

I have this:

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;
    }
}

And I can do CRUD operations with any Question in database.
But I need to show all questions, how to get them?
in my database questions have id : 1,2,3,100. I don't think, that through all the possible Id - is acceptable ...

like image 520
LuckSound Avatar asked Apr 12 '12 13:04

LuckSound


1 Answers

You can use the extension method Query<T> from the namespace NHibernate.Linq or you can use ISession.QueryOver<T>:

var allQuestions = session.Query<Question>().ToList();
// or
var allQuestions = session.QueryOver<Question>().List();
like image 80
Daniel Hilgarth Avatar answered Nov 02 '22 12:11

Daniel Hilgarth