How to use NHibernate to add, delete, modify simple program

Source: Internet
Author: User
Tags commit httpcontext modify rollback table name create database
Program | Data first, CREATE database

Database name: Nhibernate
Use NHibernate
Go
CREATE TABLE Users (
LogonId nvarchar not NULL default ' 0 ',
Name nvarchar default NULL,
Password nvarchar () default NULL,
EmailAddress nvarchar () default NULL,
PRIMARY KEY (LogonId)
)
Go

Data table: Users



Second, the general introduction

Project Name: Webnhibernate

Interface: webform.aspx

Specific performance documents: WebForm.aspx.cs

Entity class file: EntityClass.cs

Mapping File: Userhbm.xml

Configuration file: Web.config



Third, create the Web interface

Type
Object Name
Text Property value

Label
Label1
Id:

Label
Label2
Name:

Label
Label3
Password:

Label
Label4
Email:

Label
Labmessage


Textbox
txtID


Textbox
Txtname


Textbox
Txtpassword


Textbox
Txtemail


Button
Butsave
Add to

Button
Butdel
Delete

Button
Butupdata
Modify




Iv. Creating mapping files (XML files) and entity classes

Entity classes

Using System;

Namespace Webnhibernate

{

public class Entityclass

{

private string ID;

private string UserName;

private string password;

private string EmailAddress;

Public Entityclass ()

{}

public string Id

{

get {return ID;}

set {id = value;}

}

public string UserName

{

get {return userName;}

set {userName = value;}

}

public string Password

{

get {return password;}

set {password = value;}

}

public string EmailAddress

{

get {return emailaddress;}

set {EmailAddress = value;}

}

}

}

Mapping File:

<?xml version= "1.0" encoding= "Utf-8"?>


<class name= "Webnhibernate.entityclass, Webnhibernate" table= "Users" >

<id name= "id" column= "logonid" type= "String" length= ">

<generator class= "Assigned"/>

</id>

<property name= "UserName" column= "name" type= "string" length= "M"/>

<property name= "Password" type= "string" length= "/>"

<property name= "EmailAddress" type= "String" length= "/>"

</class>


Note the point:

1. <class name= "Webnhibernate.entityclass, Webnhibernate" table= "Users" >

Webnhibernate.entityclass Representative: Entity class name

Webnhibernate representative: The assembly name of the project

Users Rep: Data table name

2. When the property list <property name= "column="/> The properties of the entity layer are not the same as the field names of the datasheet

3. Specifying an ID, which is the primary key in the datasheet, is very important, and nhibernate is to determine the uniqueness of the object by ID.



Five, add configuration content in the configuration file

1. First, add the following code below the <configuration> code of the configuration file

<configSections>

<section name= "NHibernate" type= "System.Configuration.NameValueSectionHandler, System, version=1.0.3300.0, Culture=neutral, publickeytoken=b77a5c561934e089 "/>

</configSections>

This piece of code is a must.

2. Add the following code below the </system.web> code of the configuration file

<nhibernate>

<!-Connection Data Provider-->

<add

key= "Hibernate.connection.provider"

Value= "NHibernate.Connection.DriverConnectionProvider"

/>

The <!-connection data dialect is most commonly used in Mssql2000dialect-->

<add

key= "Hibernate.dialect"

Value= "NHibernate.Dialect.MsSql2000Dialect"

/>

<!-Connection data-driven class-->

<add

key= "Hibernate.connection.driver_class"

Value= "NHibernate.Driver.SqlClientDriver"

/>

<!-Connection Database-->

<add

key= "Hibernate.connection.connection_string"

Value= "Server=yanfa1;initial catalog=nhibernate; User id=sa;password=8626798; "

/>

</nhibernate>



Vi. Implementing code


First add code to the file header
Using NHibernate;
Using Nhibernate.cfg;
1. Add Data:

Double-click the Add button

private void Butsave_click (object sender, System.EventArgs e)

{

Mcfg=new Configuration ()///Create configuration Class

Mcfg.addxmlfile (System.Web.HttpContext.Current.Server.MapPath ("Userhbm.xml"))//Indicates the mapping file Userhbm.xml

Entityclass ventity=new Entityclass ();

Ventity.id=txtid.text;

Ventity.username=txtname.text;

Ventity.password=txtpassword.text;

Ventity.emailaddress=txtemail.text;

ISession vsession= mcfg.buildsessionfactory (). Opensession ();//Create a session factory, in general you should use a single instance object to encapsulate the session factory.

ITransaction vtransaction = Vsession.begintransaction ();//create things to handle

Try

{

Vsession.save (ventity);//Add data to the database

Vtransaction.commit ();

Labmessage.text= "OK";

}

catch (Exception ex)

{

Vtransaction.rollback ();

labmessage.text= "Error" +ex. ToString ();

}

Finally

{

Vsession.close ();

}

}



2. Delete data:


Double-click the Delete button
private void Butdel_click (object sender, System.EventArgs e)

{

Mcfg=new Configuration ();

Mcfg.addxmlfile (System.Web.HttpContext.Current.Server.MapPath ("Userhbm.xml"));

ISession vsession= mcfg.buildsessionfactory (). Opensession ();

ITransaction vtransaction = Vsession.begintransaction ();

Try

{

Entityclass ventity= (Entityclass) vsession.load (typeof (Entityclass), txtid.text);//Find records in a datasheet

Vsession.delete (ventity);//delete data to database

Vtransaction.commit ();

Labmessage.text= "OK";

}

catch (Exception ex)

{

Vtransaction.rollback ();

labmessage.text= "Error";

}

Finally

{

Vsession.close ();

}

}



3. Modify Code:


Double-click the Modify button
private void Butupdata_click (object sender, System.EventArgs e)

{

Mcfg=new Configuration ();

Mcfg.addxmlfile (System.Web.HttpContext.Current.Server.MapPath ("Userhbm.xml"));

ISession vsession= mcfg.buildsessionfactory (). Opensession ();

ITransaction vtransaction = Vsession.begintransaction ();

Try

{

Entityclass ventity= (Entityclass) vsession.load (typeof (Entityclass), txtid.text);

Ventity.username=txtname.text;

Ventity.password=txtpassword.text;

Ventity.emailaddress=txtemail.text;

Vsession.update (ventity); Modifying data to a database

Vtransaction.commit ();

Labmessage.text= "OK";

}

catch (Exception ex)

{

Vtransaction.rollback ();

labmessage.text= "Error";

}

Finally

{

Vsession.close ();

}

}

Because I also just contact NHibernate soon, there are a lot of technical difficulties do not understand, but also need more efforts, is willing to discuss with you.




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.