NHibernate 入门 ASP.NET MVC 版本 v1.0

NHibernate 介绍

NHibernate官网 v5.2

开始

  1. 创建一个ASP.NET WEB MVC项目
  2. 安装nhibernate nuget包
  3. 在web.config添加nhibernate配置项
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<!-- Add this element -->
	<configSections>
		<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
	</configSections>
	<!-- Add this element -->
	<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
	<session-factory>
		<!-- 数据库驱动 -->
		<property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
		<!-- 数据库链接字符串 -->
		<property name="connection.connection_string">Server=localhost\SQLEXPRESS;initial catalog=quickstart;Integrated Security=True
		</property>
		<!-- 映射配置 -->
		<mapping assembly="QuickStart" />
	</session-factory>
	</hibernate-configuration>
<!-- Leave the other sections unchanged -->
<system.web>
...
</system.web>
</configuration>
  1. 数据库表结构
Column  | Type         | Modifiers
--------+--------------+----------------------
 CatId  | char(32)     | not null, primary key
  Name  | nvarchar(16) | not null
   Sex  | nchar(1)     |
Weight  | real         |
  1. 创建一个Cat映射类
public class Cat
{
	public virtual string Id { get; set; }
	public virtual string Name { get; set; }
	public virtual char Sex { get; set; }
	public virtual float Weight { get; set; }
}
  1. 添加一个映射配置文件Cat.hbm.xml,并将文件属性【内容】改为嵌入的资源
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="QuickStart" assembly="QuickStart">
	<class name="Cat" table="Cat">
		<!-- A 32 hex character is our surrogate key. It's automatically generated by NHibernate with the UUID pattern. -->
		<id name="Id">
			<column name="CatId" sql-type="char(32)" not-null="true"/>
			<generator class="uuid.hex" />
		</id>
		<!-- A cat has to have a name, but it shouldn't be too long. -->
		<property name="Name">
			<column name="Name" length="16" not-null="true" />
		</property>
		<property name="Sex" />
		<property name="Weight" />
	</class>
</hibernate-mapping>
  1. 创建NHibernateHelper类
public sealed class NHibernateHelper
{
    private const string CurrentSessionKey = "nhibernate.current_session";
    private static readonly ISessionFactory _sessionFactory;
    static NHibernateHelper()
    {
        _sessionFactory = new Configuration().Configure().BuildSessionFactory();
    }
    public static ISession GetCurrentSession()
    {
        var context = HttpContext.Current;
        var currentSession = context.Items[CurrentSessionKey] as ISession;
        if (currentSession == null)
        {
            currentSession = _sessionFactory.OpenSession();
            context.Items[CurrentSessionKey] = currentSession;
        }
        return currentSession;
    }
    public static void CloseSession()
    {
        var context = HttpContext.Current;
        var currentSession = context.Items[CurrentSessionKey] as ISession;
        if (currentSession == null)
        {
            // No current session
            return;
        }
        currentSession.Close();
        context.Items.Remove(CurrentSessionKey);
    }
    public static void CloseSessionFactory()
    {
        if (_sessionFactory != null)
        {
            _sessionFactory.Close();
        }
    }
}
  1. 在控制器里添加代码
public ActionResult Index()
{
    ISession session = NHibernateHelper.GetCurrentSession();
    try
    {
        using (ITransaction tx = session.BeginTransaction())
        {
            var princess = new Cat
            {
                Name = "Princess",
                Sex = 'F',
                Weight = 7.4f
            };
            session.Save(princess);
            tx.Commit();
        }
    }
    finally
    {
        NHibernateHelper.CloseSession();
    }
    return View();
}
  1. 运行后查看数据库数据是否插入成功
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值