Summary
NHibernate supports LINQ queries starting from 3.0. Writing LINQ to NHibernate queries is as flexible as writing. NET LINQ code, which makes it easy to implement complex queries. This article uses LINQ to NHibernate to rewrite all previous queries.
The code of this article can be downloaded to nhibernate query
1. Create IQueryable object, return all customer object information
1 Public Ilist<customer> queryalllinq ()2 {3 return Session.query<customer>(). ToList (); 4 }
- To add a reference to NHIBERNATE.LINQ in your code
- The IQueryable object is deferred-loaded
- The ToList method represents immediate execution and gets the Ilist<customer> collection
2. Create aliases
1 Public Ilist<customer> queryalllinq ()2 {3 return (from inselect c). ToList (); 4 }
3. The specified object returns an array
1 Public ilist<int> selectidlinq ()2 {3 var query = Session.query<customer> (). Select (c = c.id). Distinct (). ToList (); 4 return query. ToList (); 5 }
The distinct method returns a sequence of non-repeating items.
4. Add Query criteria
1 PublicIlist<customer> Getcustomerbynamelinq (stringFirstName,stringlastName)2 {3 returnSession.query<customer> (). Where (c = c.firstname = = FirstName && C.lastname = =lastName). ToList ();4 }5 6 PublicIlist<customer>getcustomersstartwithlinq ()7 {8 varquery = fromCinchSession.query<customer> ()whereC.firstname.startswith ("J")SelectC;9 returnquery. ToList ();Ten}
5. ORDER BY
1 Public Ilist<customer> getcustomersorderbylinq ()2 {3 var from inch by Select C; 4 return query. ToList (); 5 }
6. Related queries
1 PublicIlist<ordercount>selectordercountlinq ()2 {3 varquery = Session.query<customer> (). Select (g =NewOrderCount {CustomerId = g.id, Count =G.orders.count ()});4 returnquery. ToList ();5 }6 7 PublicIlist<customer>getcustomersordercountgreaterthanlinq ()8 {9 varquery = Session.query<customer> (). Where (c = c.orders.count >2);Ten returnquery. ToList (); One } A - PublicIlist<customer>getcustomersorderdategreatthanlinq (DateTime orderDate) - { the varquery = Session.query<customer> (). Where (c = c.orders.any (o = o.ordered >orderDate)); - returnquery. ToList (); -}
Because the. Net method cannot return an anonymous class object and an object that contains an anonymous class object, the OrderCount class is added, and the Selectordercountlinq method returns the Ilist<ordercount> object.
1 Public class OrderCount 2 {3public intgetset;} 4 Public int Get Set ; } 5 }
Conclusion
LINQ to NHibernate is based on. NET LINQ and is very flexible. All collection operations provided by. NET LINQ are provided by LINQ to NHibernate. Use it to complete most nhibernate queries. The next article describes query over queries for NHibernate 3.2.
NHibernate Series Article 24: NHibernate Query LINQ query (with program download)