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


摘要

NHibernate從3.0開始支持Linq查詢。寫Linq to NHibernate查詢就跟寫.net linq代碼一樣,非常靈活,可以很容易實現復雜的查詢。這篇文章使用Linq to NHibernate重寫之前所有的查詢。

本篇文章的代碼可以到NHibernate查詢下載

1、創建IQueryable對象,返回所有Customer對象信息

1         public IList<Customer> QueryAllLinq()
2         {
3             return Session.Query<Customer>().ToList();
4         }
  • 要在代碼中添加對NHibernate.Linq的引用
  • IQueryable對象是延遲加載的
  • ToList方法表示立即執行,得到IList<Customer>集合

2、創建別名

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

3、指定對象返回數組

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

Distinct方法返回無重復項目的序列。

4、添加查詢條件

 1         public IList<Customer> GetCustomerByNameLinq(string firstName, string lastName)
 2         {
 3             return Session.Query<Customer>().Where(c => c.FirstName == firstName && c.LastName == lastName).ToList();
 4         }
 5 
 6         public IList<Customer> GetCustomersStartWithLinq()
 7         {
 8             var query = from c in Session.Query<Customer>() where c.FirstName.StartsWith("J") select c;
 9             return query.ToList();
10         }

5、order by

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

6、關聯查詢

 1         public IList<OrderCount> SelectOrderCountLinq()
 2         {
 3             var query = Session.Query<Customer>().Select(g => new OrderCount { CustomerId = g.Id, Count = g.Orders.Count() });
 4             return query.ToList();
 5         }
 6 
 7         public IList<Customer> GetCustomersOrderCountGreaterThanLinq()
 8         {
 9             var query = Session.Query<Customer>().Where(c => c.Orders.Count > 2);
10             return query.ToList();
11         }
12 
13         public IList<Customer> GetCustomersOrderDateGreatThanLinq(DateTime orderDate)
14         {
15             var query = Session.Query<Customer>().Where(c => c.Orders.Any(o => o.Ordered > orderDate));
16             return query.ToList();
17         }

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

1     public class OrderCount
2     {
3         public int CustomerId { get; set; }
4         public int Count { get; set; }
5     }

 

結語

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM