Setup and run a simple nhibernate example

1. Download nhibernate (version 3.1.0 GA, latest 3.3.1 doens't have lazy loading related dlls) from http://sourceforge.net/projects/nhibernate/files/NHibernate/

2. Create a console application by adding following dlls

3. Create a class named

namespace TstDBConnection.Entities{
    public class Course{
        public virtual Guid Id { get; set; }
        public virtual string Name { get; set; }
        public virtual DateTime CreatedDate { get; set; }
    }
}

4. Create a xml file named Course.hbm.xml. (right click the file, select Properties and set "Build Action" as "Embedded Resource")

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="TstDBConnection.Entities" assembly="TstDBConnection">
  <class name="Course" table="Course">
    <id name="Id" column="Id">
      <generator class="guid.comb"/>
    </id>
    <property name="Name" column="Name"></property>
    <property name="CreatedDate" column="CreatedOn"></property>
  </class>
</hibernate-mapping>

5. Adding following code into main method

            log4net.Config.XmlConfigurator.Configure(); // log4net
            Configuration configuration = new Configuration();
            configuration.Configure();
            ISessionFactory sessionFactory = configuration.BuildSessionFactory();

            //Use NHibernate to create an entity and get a list of all entities
            using (ISession session = sessionFactory.OpenSession())
            {
                Course emp = new Course()
                {
                    Name = "English",
                    CreatedDate = DateTime.Now
                };
                session.Save(emp);
                session.Flush();

                var query = from course in session.Query<Course>()
                            select course;
                IList<Course> courses = query.ToList();
            }

            //Shut down NHibernate
            sessionFactory.Close();

6. Run create DB script below:

USE [Test]
GO

/****** Object:  Table [dbo].[Course]    Script Date: 08/30/2012 13:29:35 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Course]') AND type in (N'U'))
DROP TABLE [dbo].[Course]
GO

USE [Test]
GO

/****** Object:  Table [dbo].[Course]    Script Date: 08/30/2012 13:29:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Course](
    [Id] [uniqueidentifier] NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [CreatedOn] [datetime] NOT NULL
) ON [PRIMARY]

GO

原文地址:https://www.cnblogs.com/webglcn/p/2663574.html