Nhib.pdf beginner's Guide (2): A complete example

Source: Internet
Author: User
Prepare the development environment

Operating System:Windows Vista, Windows 7, Windows Server 2003, or Windows Server 2008

IDE:Vs 2010 professional, vs C #2010 express or vs basic 2010 Express

If you do not use Visual Studio, you can use the open-source ide:

    • Monodevelop is an IDE designed specifically for C # And other. NET languages. You can download it from here.
    • Sharpdevelop, which is a free IDE for C #, VB. NET and Boo projects on the. NET platform ., You can download it from here.

Database:Nhib.pdf supports mainstream relational databases, such as Oracle, ms SQL Server, MySQL and so on. We use ms SQL Server as our RDBMS, and SQLite will be used in subsequent tests. I installed ms SQL server2008.

Prepare nhib.pdf:Download from fluent nhib.pdf, includingProgramAll required files.

Define Model

This example is called the product inventory system. We want to use this program to manage the product list of a small grocery store. Products are grouped by category. A category consists of a name and a brief description. The product has a name, brief description, category, unit price, re-sorting level, and an identifier to determine whether the product is dismounted. Each product and category has an ID. If you draw the class diagram of the model we describe, as shown in:

Note: Only the Professional version designer of VS is available, and the free Express version is unavailable.

Let's complete this simple product inventory system ).

1. Create a folder named nh3beginnersguide in the computer, and create a new folder named Lib in it. Decompress the downloaded fluent nhib.pdf to the Lib folder.

2. Open Visual Studio and create an ASP. net mvc 3 web application. In the "new ASP. net mvc 3 Project" dialog box that appears, select Internet application and click "OK ".

3. Create the category and product classes in the models folder respectively,CodeAs follows:

Public classCategory{Public Virtual intId {Get;Set;}Public Virtual stringName {Get;Set;}Public Virtual stringDescription {Get;Set;}}

 

 Public class  Product { Public Virtual int Id { Get ; Set ;}Public Virtual string Name { Get ; Set ;} Public Virtual string Description { Get ; Set ;} Public Virtual  Category CATEGORY { Get ; Set ;} Public Virtual decimal Unitprice { Get ; Set ;}Public Virtual int Reorderlevel { Get ; Set ;} Public Virtual bool Discontinued { Get ; Set ;}}

 

Ing model

There are different methods for defining mappings. The most common method is not defined in XML format, but in code. In this example, select the latter.

1. Reference fluentnhibernate. dll and Nhibernate. dll in the project.

2. Create categorymap and productmap classes in models, respectively, so that they all inherit from the classmap <t> class. The Code is as follows:

Public classCategorymap:Classmap<Category> {PublicCategorymap () {ID (x => X. ID); Map (x => X. name ). length (50 ). not. nullable (); Map (x => X. description );}}

 

Public classProductmap:Classmap<Product> {PublicProductmap () {ID (x => X. ID); Map (x => X. name ). length (50 ). not. nullable (); Map (x => X. description); Map (x => X. unitprice ). not. nullable (); Map (x => X. reorderlevel); Map (x => X. discontinued); References (x => X. category ). not. nullable ();}}

 

Create database architecture

Instead of manually creating the database architecture, we asked nhib.pdf to create it for us. All we need to do is create an empty database.

1. Open SSMs and select SQL Server Authentication.

2. Create an empty database named Pis.

3. Create a New nhibernatehelper class in the models folder. The Code is as follows:

 Public class Nhibernatehelper { Public static  Isessionfactory Createsessionfactory (){ Return  Fluently . Configure (). Database ( Mssqlconfiguration . Mssql2008. connectionstring (C => C. fromconnectionstringwithkey ( "Pisconn" ). Mappings (M => M. fluentmappings. addfromassemblyof < Productmap > (). Exposeconfiguration (createschema). buildsessionfactory ();} Private Static void Createschema (Configuration CFG ){ VaR Schemaexport = New  Schemaexport (CFG ); // Schemaexport. setoutputfile ("C: \ ABC. SQL "); Schemaexport. Create ( False ,

True

 
);}}

I will not explain this code.Article. The comment line is the database creation script generated by nhib.pdf.

4. Open Web. config and add the following code in the <connectionstrings> </connectionstrings> section:

<AddName="Pisconn"Connectionstring="Data Source =.; initial catalog = Pis; user id = sa; Password = Sasa; Integrated Security = true"Providername="System. Data. sqlclient"/>

5. Create a New cateogrycontroller and select empty controller as the template. Add the following code to index:

 
VaRFactory =Nhibernatehelper. Createsessionfactory ();

6. Create the view of the index, run the program, and nhib.pdf will automatically create the database architecture.

Find the ABC. SQL file in drive C, and the code in it is as follows:

    If  Exists (  Select 1 From  Sys  .  Objects  Where  Object_id  =  Object_id  (  N' [fk1f94d86a856f978e]'  ) And  Parent_object_id  =  Object_id (  '[Product]'  ))  ALTER TABLE  [Product]  Drop Constraint  Fk1f94d86a856f978e  If  Exists (  Select  *  From  DBO  .  Sysobjects  Where  ID  = Object_id  (  N' [category]'  ) And  Objectproperty  (  ID  ,  N 'isusertable'  ) = 1 )  Drop table  [Category]  If  Exists (  Select  * From  DBO  .  Sysobjects  Where  ID  =  Object_id  (  N' [product]'  ) And  Objectproperty  (  ID  ,  N 'isusertable'  ) = 1 ) Drop table  [Product]  Create Table  [Category]  (  ID  Int identity  Not null,  Name  Nvarchar  ( 50 ) Not null,  Description nvarchar  ( 255 ) Null,  Primary Key (  ID  ))  Create Table  [Product]  (  ID  Int identity  Not null,  Name  Nvarchar  ( 50 ) Not null,  Description nvarchar  ( 255 ) Null, Unitprice  Decimal  ( 19 , 5 ) Not null,  Reorderlevel  Int  Null,  Discontinued  Bit  Null,  Category_id  Int  Not null,  Primary Key  (  ID ))  ALTER TABLE  [Product]  Add Constraint  Fk1f94d86a856f978e  Foreign key  (  Category_id  )  References  [Category] 

7. After creating the database architecture, set schemaexport. Create (False,True); Change to schemaexport. Create (False,FalseIn this way, the database architecture will not be regenerated when the program is started.

Implement program crud

First, insert

1. Add create action in categorycontroller. The Code is as follows:

 /// Get:/category/create  Public  Actionresult Create (){ Return View ();}[ Httppost ] Public  Actionresult Create ( Category Category ){ If (Category. Name = Null ) {Modelstate. addmodelerror ( "" ,"Category name cannot be blank" ); Return View (category );} Else { VaR Factory = Nhibernatehelper . Createsessionfactory (); Using ( VaR Session = factory. opensession () {session. Save (category );} Return Redirecttoaction ( "Index" );}}

2. Add the corresponding view and the code will not be posted. Run the command to view the effect:

Second, implement query

1. Modify index action. The Code is as follows:

 
/// Get:/category/PublicActionresultIndex (){VaRFactory =Nhibernatehelper. Createsessionfactory ();Ienumerable<Category> Categories;Using(VaRSession = factory. opensession () {categories = session. queryover <Category> (). List ();}ReturnView (categories );}

2. This step is the same as above, and you can directly view the running effect:

Third, implement modifications

1. Add edit action. The Code is as follows:

 Public Actionresult Edit ( Int ID ){ VaR Factory = Nhibernatehelper . Createsessionfactory (); Category Category; Using ( VaR Session = factory. opensession () {Category = session. Get < Category > (ID );} Return View (category );}[ Httppost ] Public Actionresult Edit ( Category Category ){ VaR Factory = Nhibernatehelper . Createsessionfactory (); Using ( VaR Session = factory. opensession ()){ Itransaction Transactioin = session. begintransaction (); Try {Session. Update (category); transactioin. Commit ();} Catch ( Exception ) {Transactioin. rollback ();}} Return Redirecttoaction ( "Index" );}

2. Check the running effect as follows:

Fourth, implement Deletion

1. Add Delete action. The Code is as follows:

 Public  Actionresult Delete ( Int ID ){ VaR Factory = Nhibernatehelper . Createsessionfactory (); Using ( VaR Session = factory. opensession ()){Itransaction Transaction = session. begintransaction (); Try { VaR Category = session. Get < Category > (ID); Session. Delete (category); transaction. Commit ();} Catch ( Exception ) {Transaction. rollback ();}} Return Redirecttoaction ( "Index" );}

2. Run the command directly without adding a view. view the result:

Click OK to delete the record.

Summary

I wanted to directly translate the examples in the book nhib1_3 beginner's guid. I decided to write an example myself. This example only implements functions without considering too many things, which is equivalent to Hello world. I will explain a lot of the above knowledge in detail later, because I have just been in touch with it, and many things have not been too clear. I believe that with the continuous development of learning, we will also have a better understanding of nhib.pdf.

Finally, I hope all of you can point out my shortcomings and pray for common progress.

Source code: http://files.cnblogs.com/nianming/NH3BeginnersGuide.rar

Note: To reduce the file size, I did not include the files in lib into the aboveSource code

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.