MVC+Nhibernate+spring.net(一)

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

第一步:建立一个mvc项目web

第二步:搭建简单的三层sql

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

 

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

由于咱们使用的sqlserver,因此这个配置文件的名字改为Hibernate.cfg.xmlmvc

 

<?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的属性设置为若是较新就复制app

如今在model层中建立实体类和映射文件ide

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

 

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

 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();
        }

如今运行一下看是否是把全部的数据都查到了

数据已经显示出来了。 

相关文章
相关标签/搜索