1. 程式人生 > >基礎增刪改查-NHibernate入門到精通系列3

基礎增刪改查-NHibernate入門到精通系列3

從今天開始,我們將進入NHibernate開發學習中,首先來一些NHibernate的增刪改查操作,把這幾個學會了,基礎就打好了。
有時間也可以學學國產的CYQ.Data 資料框架,也是相當優秀的一款框架!

下面我們按以下步驟進行操作:

1.實體類與Xml對映

2.NHibernate工具生成對應的表結構

3.編寫資料庫訪問物件DAO

4.單元測試一下增、刪、該、查方法

一:新建專案,如下圖:

  


 二:編寫實體類

    public class Product
    {
        public virtual Guid ID { get; set; }
        public virtual string Code { get; set; }
        public virtual string Name { get; set; }
        public virtual string QuantityPerUnit { get; set; }
        public virtual string Unit { get; set; }
        public virtual decimal SellPrice { get; set; }
        public virtual decimal BuyPrice { get; set; }
        public virtual string Remark { get; set; }
    }
三:對映到Xml中:



<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain" namespace="Domain">
  <class name="Product" table="T_Product" lazy="true" >
    <id name="ID" column="ID" type="Guid" >
      <generator class="assigned" />
    </id>

    <property name="Code" type="string">
      <column name="Code" length="51"/>
    </property>

    <property name="Name" type="string">
      <column name="Name" length="52"/>
    </property>
   
    <property name="QuantityPerUnit" type="string">
      <column name="QuantityPerUnit" length="53"/>
    </property>

    <property name="Unit" type="string">
      <column name="Unit" length="54"/>
    </property>


    <property name="SellPrice" type="decimal">
      <column name="SellPrice" precision="14" scale="2"/>
    </property>

    <property name="BuyPrice" type="decimal">
      <column name="BuyPrice" precision="14" scale="2"/>
    </property>

    <property name="Remark" type="string">
      <column name="Remark" length="191"/>
    </property>

  </class>
</hibernate-mapping>

四:將xml當成資源嵌入,如下圖:


 五:建立Web測試專案,如下圖:


六:引用相關的程式集,如下圖:

 

 

七:將專案複製貼上NHibernate配置模板到專案中並修改該檔案的屬性為“始終複製”,如下圖:




八:準備初始化資料庫表結構[NHibernateInit.cs]

[TestFixture]
    public class NHibernateInit
    {
        [Test]
        public void InitT()
        {
            var cfg = new NHibernate.Cfg.Configuration().Configure("Config/hibernate.cfg.xml");
            using (ISessionFactory sessionFactory = cfg.BuildSessionFactory()) { }
        }
    }

九:LinFu.DynamicProxy.dll”和“NHibernate.ByteCode.LinFu.dll”拷貝到專案中並修改生成方式,如下圖:



 

    

十:除錯並啟動外部程式,如下圖:


十一:新建資料庫,如下圖:

 

 

十一:定位到“NHibernateTest.dll”的程式集,啟動單元測試,如下圖:


十二:資料庫表預設被建立好了!

 

 
十二:新建資料庫訪問物件專案,如下圖:


 

十三:引用專案dll,實現IProductDao介面和 ProductDao類

  
ProductDao
 public interface IProductDao
    {
        object Save(Product entity);

        void Update(Product entity);

        void Delete(Product entity);

        Product Get(object id);

        Product Load(object id);

        IList<Product> LoadAll();
    }


 public class ProductDao : IProductDao
    {
        private ISessionFactory sessionFactory;

        public ProductDao()
        {
            var cfg = new NHibernate.Cfg.Configuration().Configure("Config/hibernate.cfg.xml");
            sessionFactory = cfg.BuildSessionFactory();
        }

        public object Save(Domain.Product entity)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                var id = session.Save(entity);
                session.Flush();
                return id;
            }
        }

        public void Update(Domain.Product entity)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                session.Update(entity);
                session.Flush();
            }
        }

        public void Delete(Domain.Product entity)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                session.Delete(entity);
                session.Flush();
            }
        }

        public Domain.Product Get(object id)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                return session.Get<Domain.Product>(id);
            }
        }

        public Domain.Product Load(object id)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                return session.Load<Domain.Product>(id);
            }
        }

        public IList<Domain.Product> LoadAll()
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                return session.Query<Domain.Product>().ToList();
            }
        }
}

十四:編寫測試類[ProductDaoTest]:

[TestFixture]
    public class ProductDaoTest
    {
        private IProductDao productDao;

        [SetUp]
        public void Init()
        {
            productDao = new ProductDao();
        }

        [Test]
        public void SaveTest()
        {
            var product = new Domain.Product
            {
                ID = Guid.NewGuid(),
                BuyPrice = 10M,
                Code = "ABC123",
                Name = "電腦",
                QuantityPerUnit = "20x1",
                SellPrice = 11M,
                Unit = "臺"
            };

            var obj = this.productDao.Save(product);

            Assert.NotNull(obj);
        }

        [Test]
        public void UpdateTest()
        {
            var product = this.productDao.LoadAll().FirstOrDefault();
            Assert.NotNull(product);

            product.SellPrice = 12M;

            Assert.AreEqual(12M, product.SellPrice);
        }

        [Test]
        public void DeleteTest()
        {
            var product = this.productDao.LoadAll().FirstOrDefault();
            Assert.NotNull(product);

            var id = product.ID;
            this.productDao.Delete(product);
            Assert.Null(this.productDao.Get(id));
        }

        [Test]
        public void GetTest()
        {
            var product = this.productDao.LoadAll().FirstOrDefault();
            Assert.NotNull(product);

            var id = product.ID;
            Assert.NotNull(this.productDao.Get(id));
        }

        [Test]
        public void LoadTest()
        {
            var product = this.productDao.LoadAll().FirstOrDefault();
            Assert.NotNull(product);

            var id = product.ID;
            Assert.NotNull(this.productDao.Get(id));
        }

        [Test]
        public void LoadAllTest()
        {
            var count = this.productDao.LoadAll().Count;
            Assert.True(count > 0);
        }
}
十五,執行單元測試,大功告成,如下圖:

經過以上十五步之後,終於把這基本的操作給折騰好了,反正NHibernate就是這麼複雜又強大的,喜歡折騰的趕緊試試吧!