標籤:
摘要
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 OrderCount2 {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查詢。
NHibernate系列文章二十四:NHibernate查詢之Linq查詢(附程式下載)