MVC+Nhibernate+spring.net(一)

所用数据库是我之前所写的Nhibernate入门篇的数据库https://www.cnblogs.com/pandorabox/p/PandoraBox.html

第一步:创建一个mvc项目

第二步:搭建简单的三层

第三步:在dal层和web层分别添加nhibernate的程序包

 第四步:找到下载的nhibernate中的这个文件复制到web层的根目录

因为我们使用的sqlserver,所以这个配置文件的名字改成Hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- 
This template was written to work with NHibernate.Test.
Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it 
for your own use before compile tests in VisualStudio.
-->
<!-- This is the System.Data.dll provider for SQL Server -->
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="NHibernate.Test">
        <property name="connection.driver_class">NHibernate.Driver.Sql2008ClientDriver</property>
        <property name="connection.connection_string">
      Server=.;database=NHibernateDemoDB;uid=sa;pwd=root
    </property>
    <!--方言:使用某些特定数据库平台的特性-->
        <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <!---指定映射文档所在的程序集-->
    <mapping assembly="Model" />
  </session-factory>
</hibernate-configuration>

将nhibernate的属性设置为如果较新就复制

现在在model层中创建实体类和映射文件

代码我就不展示了,在我上一篇文章里面

第五步:在dal层写一个nhibernate的帮助类

 public class Nhelper
    {
        private static ISessionFactory _sessionFactory;
        public static ISessionFactory SessionFactory
        {
            get
            {
                //实例化session
                return _sessionFactory == null ? (new Configuration()).Configure().BuildSessionFactory() : _sessionFactory;
            }
        }
    }

第六步:在dal层写empdal的方法

public class EmpDal
    {
        public IList<Emp> GetList(Expression<Func<Emp,bool>> where)
        {
            using (ISession session = Nhelper.SessionFactory.OpenSession())
            {
                return session.Query<Emp>().Select(x => new Emp
                {
                    EmpId = x.EmpId,
                    EmpName = x.EmpName,
                    EmpDate = x.EmpDate
                }).Where(where).ToList();
            }
        }

第七步:写bll层的方法

public class EmpBll
    {
        public EmpDal empDal;
        public EmpBll()
        {
            this.empDal = new EmpDal();
        }
        public IList<Emp> GetCustomersList(Expression<Func<Emp, bool>> where)
        {
            return empDal.GetList(where);
        }
    }

第八步:写控制器层的代码

public ActionResult Index()
        {
            EmpBll bll = new EmpBll();
            var result = bll.GetCustomersList(u => true);
            return View();
        }

现在运行一下看是不是把所有的数据都查到了

数据已经显示出来了。 

原文地址:https://www.cnblogs.com/pandorabox/p/10148780.html