1. 程式人生 > >MVC+Nhibernate+spring.net增刪查改(一)

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

現在執行一下看是不是把所有的資料都查到了

資料已經顯示出來了。