如何通过NHibernate从表中获取数据?

时间:2012-02-29 09:28:00

标签: c# hibernate nhibernate

我在我的项目NHibernate中使用了这样的:

public class DBHelper
    {
        private static ISessionFactory sessions;

        public static void Configure()
        {            
            sessions = new Configuration().Configure().AddClass(typeof(Clients)).BuildSessionFactory();
            //ISessionFactory factory = Fluently.Configure().Mappings(m => m.FluentMappings.AddFromAssemblyOf<Clients>()).Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromConnectionStringWithKey(DBConnection.GetConnectionString())).BuildSessionFactory();
        }

        public static void Insert(Clients pb)
        {            
            using (ISession session = sessions.OpenSession())           
            using (ITransaction tx = session.BeginTransaction())
            {                
                session.Save(pb);                
                tx.Commit();
            }
        }

        public static void UpdateContact(Clients pb)
        {
            using (ISession session = sessions.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                session.Update(pb);
                tx.Commit();
            }
        }

        public static void DeleteContact(Clients pb)
        {
            using (ISession session = sessions.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                session.Delete(pb);
                tx.Commit();
            }
        }
    }

我有树简单方法:插入,删除,保存。 现在我需要从DB表中获取所有数据或者从模拟中获取一些数据      从客户端中选择*,其中id ='...'

1 个答案:

答案 0 :(得分:9)

您的选择是:

就个人而言,我非常喜欢QueryOver API:

var clients = session.QueryOver<Clients>().Where(x => x.Name == "Foobar").List();

如果您只需要通过其ID获取实体,则可以使用Get or Load

var client = session.Get<Clients>(5);

如果您搜索NHibernate教程,您肯定会找到很多信息。我听说过Summer Of NHibernate screencasts的好消息,但我个人还没有见过它们。