1, create a session factory (session factory)
#region //******************** Create a session factory--- create session factory*******************//Private voidBtncreatesessionfactory_click (ObjectSender,routedeventargs e) {varFactory =createsessionfactory ();}Privateisessionfactory createsessionfactory () {//*********************sql server************************////return fluently.configure ()//. Database (Mssqlconfiguration//. MsSql2012//. ConnectionString (connstring))//. Mappings (m = m.fluentmappings//. Addfromassemblyof<productmap> ())//. Buildsessionfactory ();//*********************sqlite************************//returnfluently.configure (). Database (SQLiteConfiguration.Standard.UsingFile (DataSource)). Mappings (M=m.fluentmappings.addfromassemblyof<ProductMap>())//. Exposeconfiguration (Createschema)////because Createschema is a database that has been remapped once, when there is always only one value when adding data to a table, the others will disappear, and the new data will be added when there is no such sentence. . Buildsessionfactory ();}#endregion
2. Open session to operate the database (open session, Seesion. Save, session. Query operation)
#region //************************* Open the session and manipulate the database *********************////****************************** Open a session, do not operate ****************************//Private voidBtncreatesession_click (ObjectSender,routedeventargs e) {varFactory =createsessionfactory ();using(varSession =Factory. Opensession ()) {//Do something with the session}}//****************************** Open a session to add operations to the database ****************************//Private voidBtnaddcategory_click (ObjectSender,routedeventargs e) {varFactory =createsessionfactory ();using(varSession =Factory. Opensession ()) {varCategory =NewCategory{name=txtcategoryname.text,description=txtcategorydescription.text};session. Save (category);}}//************************** Open a session to check the database ************************************//Private voidBtnloadcategories_click (Objectsender, RoutedEventArgs e) {varFactory =createsessionfactory ();using(varSession =Factory. Opensession ()) {varCategories = Session. Query<category>(). (c=c.name). ToList (); Lstcategories.itemssource=Categories;lstcategories.displaymemberpath="Name";}}#endregion
3. Summary
Through simple instance operation, we learned the simple process of nhibernate to SQLite operation, as follows:
1. Define a model
2. Define how databases work (Database Schema)
3. Mapping the model to the database (Mapping the "model to the") (Is this the essence of ORM?) I hope the great God to answer the next)
4. Session usage and Transaction enablement (Sessions and transactions)
5. Testing (TEST)
If there is an understanding of the wrong, please the great god pointing.
Nhibernate+sqlite Learning Note (ii) + use fluent NHibernate to establish session factory and manipulate the database (open session)