Nhibernate快速开始,IIS ASP.NET MVC项目,MSSQL

刚接触Nhibernate,(Nhibernate是什么,哈哈,百度,以下简称NH)走了不少弯路,写下过程,参考内容
官网 Chapter 1. Quick-start with IIS and Microsoft SQL Server,不过它是英文的,看起来有点难,而且它操作步骤写得不细,概念涉及较多。既然是用框架,简单一二三就好。
步骤:
1 新建asp.mvc 项目QuickStart,注意框架选4.6.1以上,因为新版的NH要4.6.1以上
2 引入NHibernate,这个有很多方法,我喜欢用NuGet包管理器–管理解决方案的NuGet程序包来安装NH。这个直观,不用记命令,敲字符。

引入NH
在这里插入图片描述
因为我的项目已引入NH,所以箭头当中的“安装”是灰色的。点安装之后,按照提示,很容易就引入了。
3.编写NHibernate配置文件
3.1 在QuickStart的根目录下添加hibernate.cfg.xml文件
3.2 设置 hibernate.cfg.xml 的属性为始终复制和 嵌入的资源,这步必须要,否则运行起来会报错,提示找不到该文件
在这里插入图片描述

在这里插入图片描述
3.3 hibernate.cfg.xml 内容如下

<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
	<session-factory>
		<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
		<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
		<property name="connection.connection_string">Data Source=localhost;user=sa;password=123456;Initial Catalog=QuickStart</property>
		<property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
		<!--dialect的类型参考https://github.com/nhibernate/nhibernate-core/tree/master/src/NHibernate/Dialect-->
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">update</property>
		<mapping  assembly="QuickStart"/>
	</session-factory>
</hibernate-configuration>

注意:我的机器安装的是mssql server 2019 参数也是填 NHibernate.Dialect.MsSql2012Dialect,能正确运行,对MSSQL可选择参数常用的还有
NHibernate.Dialect.MsSql2000Dialect
NHibernate.Dialect.MsSql2005Dialect
NHibernate.Dialect.MsSql2008Dialect
NHibernate.Dialect.MsSql2012Dialect
相必对应自己的版本,能选择正确的参数了。
4 编写Model Class “Cat”
类文件的位置,建议按照MVC的目录来摆放,存在Models文件里,内容如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

//namespace QuickStart.Models
namespace QuickStart  //用上面的命名空间也可以,但在映射文件里要对应,
{
    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; }
     
    }

}

官网上说,必须要有空参数的构造方法,所有的属性都必须使用virtual来修饰,这里没有空参数构造方法,也运行成功,可能是C#自动会生成这个构造方法,基础知识有点不记得了,每天大部份都是复制,粘贴。
5 编写Model的Mapping文件
位于Mapping目录下面新建文件Cat.hbm.xml文件,如同上面的要设置该文件的属性为始终复制和 嵌入的资源
内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    namespace="QuickStart" assembly="QuickStart"  default-lazy="false">

	<class name="Cat" table="Cat">    <!--注意table名称不能与MSSQL的关键字重名-->

		<!-- A 32 hex character is our surrogate key. It's automatically
            generated by NHibernate with the UUID pattern. -->
		<id name="Id">
			<column name="Id" 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>


6 编写NHibernate的帮助类,初始化NHibernate的环境,获取Session
内容如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using NHibernate;
using NHibernate.Cfg;
namespace QuickStart
{
    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();
            }
        }

        public static void save(Cat cat)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            try
            {
                using (ITransaction tx = session.BeginTransaction())
                {
                    //var princess = new Cat
                    //{
                    //    Name = "Princess",
                    //    Sex = 'F',
                    //    Weight = 7.4f
                    //};

                    session.Save(cat);
                    tx.Commit();
                }
            }
            finally
            {
                NHibernateHelper.CloseSession();
            }
        }

        public List<Cat> select( )
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            try
            {
                using (var tx = session.BeginTransaction())
                {
                    var females = session
                        .Query<Cat>()
                        .Where(c => c.Name == c.Name)
                        .ToList();
                    tx.Commit();
                    return females;
                }
                
            }
            finally
            {
                NHibernateHelper.CloseSession();
            }
        }
    }
}

7 使用它
7.1 在View - home 里新增一个视图Add,
mvc的内容就少写,偷个懒,直接用模生成代码
在这里插入图片描述
修改add.cshtml文件当的一句 如下
@using (Html.BeginForm(“add”))

@model QuickStart.Cat


<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Add</title>
</head>
<body>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    
    
    @using (Html.BeginForm("add")) 
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <h4>Cat</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Sex, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.Weight, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Weight, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Weight, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

7.2 把HomeController里增加两个方法

        public ActionResult Add()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Add(Cat cat)
        {
            NHibernateHelper.save(cat);
            return View();
        }

全类如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QuickStart.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Add()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Add(Cat cat)
        {
            NHibernateHelper.save(cat);
            return View();
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

7.3 运行
在数据库创新一个QuictStart库,可以不用建Cat表也能行,我运行的时候,按照模型类建了Cat表。
把地址里地址改成
https://localhost:44366/home/add
注意44366这个临时端口号跟你的肯定不一样,
才注意到是https,不知道你也是吗?难道asp.net mvc都 https吗?
运行界面如下,
在这里插入图片描述
点击“create",就成功,用ssms打开数据库,可以看到增加了一条数据。
没做显示,见谅。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值