NHibernate 有好几种数据库查询方式 1、原生SQL var employeeQuery = Database.Session .CreateSQLQuery("select * from Employee where FirstName = ‘John‘") .AddEntity(typeof(Employee)); var employees = employeeQuery.List<Employee>(); 2、Hibernate Query Language(HQL)HN自己的一条语言,简称HQL var employeeQuery = Database.Session .CreateQuery("select e from Employee as e"); var employees = Database.Session .CreateQuery("select e from Employee as e ") .List<Employee>(); //select e from Employee as e where e.Firstname = ‘John‘ var firstName = "John"; var employees = Database.Session .CreateQuery("select e from Employee as e where e.Firstname = ‘" + firstName + "‘") .List<Employee>(); var employeeQuery = Database.Session .CreateQuery("select e from Employee as e where e.Firstname = :firstName"); employeeQuery.SetParameter("firstName", "John"); var employees = employeeQuery.List<Employee>(); 3、Criteria API 标准API using (var transaction = database.Session.BeginTransaction()) { var employeeQuery = database.Session.CreateCriteria<Employee>(); employeeQuery.Add(Restrictions.Eq("Firstname", "john")); var employees = employeeQuery.List<Employee>(); transaction.Commit(); } using (var transaction = database.Session.BeginTransaction()) { var employees = database.Session.CreateCriteria<Employee>() .Add(Restrictions.Eq("Firstname", "john")) .List<Employee>(); transaction.Commit(); } using (var transaction = database.Session.BeginTransaction()) { var employees = database.Session.CreateCriteria<Employee>() .Add(Restrictions.Between("DateOfJoining", DateTime.Now.AddYears(-1), DateTime.Now)) .List<Employee>(); transaction.Commit(); } 4、The QueryOver API var employees = Database.Session.QueryOver<Employee>() .Where(x => x.Firstname == "John") .List<Employee>(); var employees = Database.Session .QueryOver<Employee>() .Where(x => x.DateOfJoining > DateTime.Now.AddYears(-1) && x.DateOfJoining < DateTime.Now) .List<Employee>(); 5、LINQ var employees = from e in Database.Session.Query<Employee>() where e.Firstname == "John" select e; var employees = Database.Session.Query<Employee>() .Where(e => e.Firstname == "John"); var employees = from e in Database.Session.Query<Employee>() where e.DateOfJoining > DateTime.Now.AddYears(-1) && e.DateOfJoining < DateTime.Now select e; var employees = Database.Session.Query<Employee>() .Where(e => e.DateOfJoining > DateTime.Now.AddYears(-1) && e.DateOfJoining < DateTime.Now);
时间: 2024-10-11 12:12:54