12

我有这个:

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

我可以对数据库中的任何问题进行 CRUD 操作。
但我需要展示所有问题,如何获得它们?
在我的数据库中,问题的编号为:1,2,3,100。我不认为,通过所有可能的 Id - 是可以接受的......

4

1 回答 1

25

Query<T>您可以使用命名空间中的扩展方法,NHibernate.Linq也可以使用ISession.QueryOver<T>

var allQuestions = session.Query<Question>().ToList();
// or
var allQuestions = session.QueryOver<Question>().List();
于 2012-04-12T13:37:21.993 回答