CRUD operations for ORM nhibernet framework

Source: Internet
Author: User

Basic syntax for nhibernet:

 Private ISession _session;            Public ISession Session {set {_session = value;        }} public Querycriteriaapi (ISession session) {_session = session; } #region Grammar Study//<summary>//Create Icriteria instances///</summary>//<retur Ns></returns> public ilist<customer> Createcriteria () {//nhibernate.icriteria This interface            Represents a query for a particular persisted class.            ISession is a factory used to create instances of criteria. var crit = _session.            Createcriteria (typeof (Customer)); Crit.            Setmaxresults (50); var customers = Crit.            List<customer> ();        return customers;        }///<summary>//Reduce the result set range///</summary>//<returns></returns>            Public ilist<customer> Narrowing () {//a query condition (Criterion) is an instance of the Nhibernate.icriterion interface. Class NhibernaTe.            Expression.expression defines a factory method that obtains some built-in icriterion types. var customers = _session. Createcriteria (typeof (Customer)). ADD (Restrictions.like ("Firstname", "yjing%")). ADD (Restrictions.between ("Lastname", "A%", "Y%")).            List<customer> (); Expressions (Expressions) can be grouped logically by//ilist<customer> customers = _session. Createcriteria (typeof (Customer))//. ADD (Restrictions.like ("Firstname", "yj%"))//.            ADD (restrictions.or (//Restrictions.eq ("Lastname", "l%"),//Restrictions.isnull ("Lastname") //    ))            //    .            List<customer> (); Ilist<customer> customers = _session. Createcriteria (typeof (Customer))//. ADD (restrictions.in ("Firstname", new string[] {"yjing", "Yjinglee", "Y"})//. ADD (Restrictions.disjunction ()//. ADD (Restrictions.isnull ("Lastname"))//. ADD (RestrictioNs. Eq ("Lastname", "Lee")//. ADD (Restrictions.eq ("Lastname", "XYZ"))//).            List<customer> (); Pre-fabricated condition type (subclass of expression).            You can embed SQL directly.            {alias} is a placeholder that will be replaced by the row alias of the queried entity//parameter paramname = new Parameter ("Somename", New Stringsqltype ()); Ilist<customer> customers = _session. Createcriteria (typeof (Customer))//. ADD (Expression.sql (///New SqlString (New object[]{//"lower ({alias}. Lastname) like lower ("," Lastname ",") "})," yjing% ", nhibernateutil.string)//.            List<customer> ();        return customers;        }//<summary>//ORDER BY//</summary>//<returns></returns> Public ilist<customer> Order () {//Use Icriteria.order to sort the result set, True=asc,false=desc R Eturn _session. Createcriteria (typeof (Customer)). ADD (Restrictions.likE ("Firstname", "Y%")). AddOrder (New NHibernate.Criterion.Order ("Lastname", true)). AddOrder (New NHibernate.Criterion.Order ("Firstname", false)).        List<customer> (); #endregion #region Instance to learn///<summary>//Use CRITERIAAPI to check customer///</        summary>//<param name= "FirstName" ></param>///<returns> customer list </returns> Public ilist<customer> Usecriteriaapi_getcustomersbyfirstname (string firstname) {//nhibernate1.2 Write FA//return _session. Createcriteria (typeof (Customer))//. ADD (New NHibernate.Expression.EqExpression ("Firstname", Firstname))//.            List<customer> (); NHibernate2.0//return _session. Createcriteria (typeof (Customer))//. ADD (Expression.eq ("Firstname", Firstname))//.            List<customer> (); Use the name encapsulation:. ADD (Restrictions.eq ("Name.firstname", Firstname)) return _session. Createcriteria (typeof (Customer)). ADD (Restrictions.eq ("Firstname", Firstname)).        List<customer> (); }///<summary>//Use CRITERIAAPI to check with FirstName and LastName///</summary>//&LT;PA Ram Name= "FirstName" ></param>//<param name= "LastName" ></param>//&LT;RETURNS&GT;&L T;/returns> Public ilist<customer> usecriteriaapi_getcustomersbyfirstnameandlastname (string firstname, str ing lastname) {//nhibernate1.2 notation//return _session. Createcriteria (typeof (Customer))//. ADD (New NHibernate.Expression.EqExpression ("Firstname", Firstname))//. ADD (New NHibernate.Expression.EqExpression ("Lastname", Lastname))//.            List<customer> (); NHibernate2.0//Use name encapsulation:. ADD (Restrictions.eq ("Firstname", Firstname)) return _session. Createcriteria (typeof (Customer)). ADD (Restrictions.eq ("Firstname", Firstname)). ADD (Restrictions.eq ("Lastname", Lastname)).        List<customer> (); }///<summary>///use CRITERIAAPI to obtain customers with a customer ID greater than CustomerID//</summary>//<para M name= "CustomerId" > Customer id</param>//<returns> customer list </returns> public ILIST&LT;CUSTOMER&G T Usecriteriaapi_getcutomerswithidgreaterthan (int customerId) {//nhibernate1.2 notation//return _ses Sion. Createcriteria (typeof (Customer))//. ADD (New NHibernate.Expression.GtExpression ("CustomerId", CustomerId))//.            List<customer> (); NHibernate2.0 return _session. Createcriteria (typeof (Customer)). ADD (restrictions.gt ("CustomerId", CustomerId)).        List<customer> (); } #endregion #region Transaction public ilist<customer> GetAll () {//Open things using (ITransaction tx = _session. BeginTransaction ()) {try {//COMMIT TRANSACTION TX.                    Commit ();                return null; } catch (Hibernateexception ex) {//ROLLBACK TRANSACTION TX.                   Rollback ();                Throw ex;         }}} #endregion #region Add, delete, update object public int Add (Customer model) { int id = (int) _session.         Save (model); _session.         Flush ();        return ID; public void Delete (Customer model) {_session.             Delete (model); _session.        Flush (); public void Update (Customer model) {//update _session.           Update (model); Update or save • Check if the object already exists in the session. If the object is not present, call Save (object). If the object exists, check to see if the object has changed. If the object changes,Call Update (object). _session.           Saveorupdate (model); _session.        Flush (); } #endregion #region Condition query (criteria query)//Create a criteria instance using the Createcriteria method of the ISession interface to create the Nhiberna Te.             Icriteria interface A query instance of a particular persisted class, it can also be said that ISession is the factory public ilist<customer> creater () that is used to create the criteria instance. Icriteria cria = _session.           Createcriteria (typeof (Customer)); Cria.           Setmaxresults (50); ilist<customer> list = Cria.           List<customer> ();             return list;        }///result set restriction data//using the Add method provided with the Icriteria interface the constraint expression in the restrictions class can limit the effect of some result sets. Public ilist<customer> norrawing () {ilist<customer> customers = _session. Createcriteria (typeof (Customer)). ADD (Restrictions.like ("FirstName", "y%"))//query FirstName like y%.                      ADD (Restrictions.eq ("FirstName", "yang")//Query Firstname=yang                 . ADD (Restrictions.between ("LastName", "%m", "_n")//query LastName between%m _n.           List<customer> ();        return customers; }//Result set sort//Use Icriteria.order to sort the result set, and the second parameter true to represent ASC,FALSE for Desc.         For example, the following example queries the customer object by FirstName Descending, LastName Ascending. Public ilist<customer> Orderss () {ilist<customer> customers = _session. Createcriteria (typeof (Customer)). ADD (Restrictions.like ("Fristname", "yangming")). AddOrder (New Order ("FirstName", false)///FirstName descending sort. AddOrder (New Order ("LastName", True))//LastName in ascending order.          List<customer> ();        return customers; }/* Conditional queries also support correlated queries, dynamic associative crawls (described in a one-to-many, many-to-many relationship), projection, aggregation, and grouping, offline (detached) queries and subqueries are new additions to version 2.0 * */// Based on the sample query (query by Example)//Based on the sample query (QBe,query by Example) is a special case of conditional queries, and the NHibernate.Criterion.Example class creates query conditions based on the instance you specify.         Typical usage: Create a example instance, set a value on the example instance, and return its collection of objects based on example and Settings nhibernate. Public ilist<customer> Query () {Customer customer = new Customer {firstname= "Yangyang", Lastnam            E= "Wang"}; Return _session. Createcriteria (typeof (Customer)). ADD (Example.create (Customer)).         List<customer> ();  }//You can adjust Example to make it more practical: public ilist<customer> Query (customer customer) {Example Exa = Example.create (Customer). IgnoreCase (). Enablelike ().             Setescapecharacter (' & '); Return _session. Createcriteria (typeof (Customer)). ADD (Exa).         List<customer> ();           #endregion #region Query NHibernate Query Language (HQL) public ilist<customer> Listall () { Return _session. Createcriteria ("from Customer"). list&Lt         Customer> (); } public ilist<customer> ListAll2 () {return _session. Createcriteria ("from Customer as C").          List<customer> (); The GROUP BY clause//return _session. Createcriteria ("SELECT * from Customer GROUP BY FirstName")//.         List<customer> (); DISTINCT clause//return _session. CreateQuery ("SELECT distinct c.firstname from Customer C")//.           List<customer> (); The WHERE clause//return _session. CreateQuery ("from Customer C where c.firstname= ' yjing '")//.           List<customer> (); WHERE clause with parameters///return _session. CreateQuery ("from Customer C where C.customerid >: CID")//. SetInt32 ("CID", 1)//.        List<customer> ();         } #endregion #region Paging query isessionfactory sessionfactory; Paging function public ilist<customer> GetAll (int currentpage, int pageSize) {//WonTake the current session ISession Cursession = Sessionfactory.getcurrentsession (); Icriteria cria = _session.             Createcriteria (typeof (Customer)); paging var model = Cria. Setfetchsize (pageSize). Setfirstresult (currentpage).             List<customer> ();         return model; }//Paging query//implement paging in NHibernate with Setfirstresult and setmaxresults implementation, Setfirstresult simple understanding is starting from the first few records, Setmaxresul TS is to take several records private ilist<customer> Getrecord (ilist<icriterion> queryconditions, int pageIndex, int PageS ize, String OrderField, bool isascending) {Icriteria criteria = _session.             Createcriteria (typeof (Customer)); foreach (Icriterion cri in queryconditions) {criteria.             ADD (CRI);             }//Total records int skipcount = (pageIndex-1) * pageSize; Criteria.             AddOrder (New Order (OrderField, isascending)); Criteria. Setfirstresult (Skipcount).             Setmaxresults (pageSize); return criteria.             List<customer> ();     SQL query//ilist<customer> customerlist = Session.createsqlquery ("SELECT * from Customer")// . Setfirstresult (Pagestart*pagelimit)//. Setmaxresults (Pagelimit)//. Setresulttransformer (Transformers.aliastobean<customer> ()).              List<customer> ();             return customerlist; Ilist<customer> customers = _session. Createsqlquery (""). Setfirstresult (PageIndex * pageSize). Setmaxresults (pageSize). Setresulttransformer (Nhibernate.transform.transformers.aliastobean<customer> ()).             List<customer> ();         return customers; } #endregion

CRUD operations for ORM nhibernet framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.