NHibernate系列文章二十四:NHibernate查询之Linq查询(附程序下载)

时间:2023-12-12 11:44:20

摘要

NHibernate从3.0开始支持Linq查询。写Linq to NHibernate查询就跟写.net linq代码一样,非常灵活,可以很容易实现复杂的查询。这篇文章使用Linq to NHibernate重写之前所有的查询。

本篇文章的代码可以到NHibernate查询下载

1、创建IQueryable对象,返回所有Customer对象信息

         public IList<Customer> QueryAllLinq()
{
return Session.Query<Customer>().ToList();
}
  • 要在代码中添加对NHibernate.Linq的引用
  • IQueryable对象是延迟加载的
  • ToList方法表示立即执行,得到IList<Customer>集合

2、创建别名

         public IList<Customer> QueryAllLinq()
{
return (from c in Session.Query<Customer>().ToList() select c).ToList();
}

3、指定对象返回数组

         public IList<int> SelectIdLinq()
{
var query = Session.Query<Customer>().Select(c => c.Id).Distinct().ToList();
return query.ToList();
}

Distinct方法返回无重复项目的序列。

4、添加查询条件

         public IList<Customer> GetCustomerByNameLinq(string firstName, string lastName)
{
return Session.Query<Customer>().Where(c => c.FirstName == firstName && c.LastName == lastName).ToList();
} public IList<Customer> GetCustomersStartWithLinq()
{
var query = from c in Session.Query<Customer>() where c.FirstName.StartsWith("J") select c;
return query.ToList();
}

5、order by

         public IList<Customer> GetCustomersOrderByLinq()
{
var query = from c in Session.Query<Customer>() orderby c.FirstName ascending select c;
return query.ToList();
}

6、关联查询

         public IList<OrderCount> SelectOrderCountLinq()
{
var query = Session.Query<Customer>().Select(g => new OrderCount { CustomerId = g.Id, Count = g.Orders.Count() });
return query.ToList();
} public IList<Customer> GetCustomersOrderCountGreaterThanLinq()
{
var query = Session.Query<Customer>().Where(c => c.Orders.Count > );
return query.ToList();
} public IList<Customer> GetCustomersOrderDateGreatThanLinq(DateTime orderDate)
{
var query = Session.Query<Customer>().Where(c => c.Orders.Any(o => o.Ordered > orderDate));
return query.ToList();
}

因为.net方法不能返回匿名类对象以及含有匿名类对象的对象,因此添加OrderCount类,SelectOrderCountLinq方法返回IList<OrderCount>对象。

     public class OrderCount
{
public int CustomerId { get; set; }
public int Count { get; set; }
}

结语

Linq to NHibernate基于.net Linq,非常灵活。.net Linq提供的所有集合操作,Linq to NHibernate也都提供了。使用它可以完成大部分NHibernate查询。下一篇文章介绍NHibernate 3.2的Query Over查询。