当前位置:首页 ? 亚博体育yabo

C#用NHibernate实现CRUD

2019-01-27 06:00 本站整理 浏览(76)

hibernate.cfg.xml



 
  NHibernate.Driver.SqlClientDriver
  
   Data Source=zhou;Initial Catalog=AspNetStudy;User ID=sa;Password=jerry;
  
  10
  true
  NHibernate.Dialect.MsSql2005Dialect
  true
  10
  true 1, false 0, yes 'Y', no 'N'
  
   NHibernate.ByteCode.Castle.ProxyFactoryFactory,
   NHibernate.ByteCode.Castle
  
  
 

UserInfo.hbm.xml



 
  
   
  
  
  
  
  
  
  
  
 

UserInfo.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace NHibernateDemo
{
    /// 
    /// 数据库中UserInfo表的持久化类
    /// 作者:周公
    /// 博客地址:http://blog.csdn.net/zhoufoxcn
    /// 日期:2010-03-19
    /// 
    public class UserInfo
    {
        public virtual int UserId { get; set; }
        public virtual string UserName { get; set; }
        public virtual string RealName { get; set; }
        public virtual int Age { get; set; }
        public virtual bool Sex { get; set; }
        public virtual string Mobile { get; set; }
        public virtual string Phone { get; set; }
        public virtual string Email { get; set; }
    }
}

NHibernateCRUD.cs

using System;
using System.Collections.Generic;
using System.Text;
using Iesi.Collections;
using NHibernate;
using NHibernate.Cfg;

namespace NHibernateDemo
{
    /// 
    /// 说明:这个类是为了演示NHibernate中的CRUD的用法
    /// 作者:周公(周金桥)
    /// 日期:2010-03-07
    /// 
    public class NHibernateCRUD
    {
        private ISessionFactory sessionFactory;
        public NHibernateCRUD()
        {
            sessionFactory = new Configuration().Configure().BuildSessionFactory();
        }

        public ISession GetSession()
        {
            return sessionFactory.OpenSession();
        }
        /// 
        /// 统计用户总数
        /// 
        /// 
        public int Count()
        {
            #region 方法一
            //ISession session = GetSession();
            //ISQLQuery query = session.CreateSQLQuery("select count(1) from UserInfo");
            //int count = query.List()[0];
            //session.Close();
            //return count;
            #endregion

            #region 方法二
            ISession session = GetSession();
            IQuery query = session.CreateQuery("select count(c.UserId) from UserInfo c");
            //注意:不能对于count函数不能使用query.List(),因为默认返回的数值类型是long
            //否则会抛出GenericADOException,异常描述是:Could not execute query[SQL: SQL not available]
            //InnerException: System.ArgumentException,InnerException描述是:"值“*”不是“System.Int32”类型,不能在此泛型集合中使用。\r\n参数名: value
            int count =(int)(query.List()[0]);
            session.Close();
            return count;
            #endregion
        }
        /// 
        /// 创建用户
        /// 
        /// 用户实体
        /// 
        public int Create(UserInfo info)
        {
            ISession session = GetSession();
            int newId=(int)(session.Save(info));
            session.Flush();
            session.Close();
            return newId;
        }
        /// 
        /// 读取用户信息
        /// 
        /// 用户编号
        /// 
        public UserInfo Read(int userId)
        {
            ISession session = GetSession();
            UserInfo info=session.Get(userId);
            session.Close();
            return info;
        }
        /// 
        /// 更新用户信息
        /// 
        /// 用户实体
        /// 
        public void Update(UserInfo info)
        {
            ISession session = GetSession();
            session.Update(info);
            session.Flush();
            session.Close();
        }
        /// 
        /// 删除用户
        /// 
        /// 用户编号
        /// 
        public void Delete(int userId)
        {
            ISession session = GetSession();
            //在NHibernate中支持直接使用参数值、":"+参数名、?(类似于在Access中使用参数化SQL语句的方式,给参数赋值要按照参数出现的顺序来)等几种方式
            IQuery query = session.CreateQuery("delete from UserInfo where UserId=:UserId");
            //如果采用":"+参数名方式使用参数,那么给参数赋值时不需要在参数名前加":"号,如query.SetInt32(":UserId", userId);就会报错
            query.SetInt32("UserId", userId);
            int affectedRows = query.ExecuteUpdate();
            session.Close();
            //return affectedRows;
        }

        /// 
        /// 删除用户
        /// 
        /// 用户实体
        /// 
        public void Delete(UserInfo info)
        {
            ISession session = GetSession();
            session.Delete(info);
            session.Flush();
            session.Close();
        }

        /// 
        /// 获取用户表中编号最大的用户
        /// 
        /// 
        public int GetMaxUserId()
        {
            ISession session = GetSession();
            IQuery query=session.CreateQuery("select max(UserId) from UserInfo");
            int userId=query.List()[0];
            session.Close();
            return userId;
        }
    }
}

单元测试 NHibernateTest.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using NHibernateDemo;

namespace NUnitTest
{
    [TestFixture]
    public class NHibernateTest
    {
        private NHibernateCRUD instance = null;
        [SetUp]
        public void Initialize()
        {
            instance = new NHibernateCRUD();
        }
        [Test]
        /// 
        /// 统计用户总数
        /// 
        /// 
        public void Count()
        {
            Assert.Greater(instance.Count(), 0);
        }
        [Test]
        /// 
        /// 创建用户
        /// 
        /// 用户实体
        /// 
        public void Create()
        {
            UserInfo info = new UserInfo()
            {
                Age = 12,
                Email = "zzz@ccav.com",
                Mobile = "13812345678",
                Phone = "01012345678",
                RealName = "测试" + DateTime.Now.Millisecond.ToString(),
                Sex = true,
                UserName = "zhoufoxcn" + DateTime.Now.Millisecond.ToString()
            };
            instance.Create(info);
        }
        [Test]
        /// 
        /// 读取用户信息
        /// 
        /// 用户编号
        /// 
        public void Read()
        {
            UserInfo info = instance.Read(1);
            Assert.NotNull(info);
        }
        [Test]
        /// 
        /// 更新用户信息
        /// 
        /// 用户实体
        /// 
        public void Update()
        {
            UserInfo info = instance.Read(1);
            info.RealName = "测试" + DateTime.Now.Millisecond.ToString();
            instance.Update(info);
        }
        [Test]
        /// 
        /// 删除用户
        /// 
        /// 用户编号
        /// 
        public void DeleteByID()
        {
            int userId = instance.GetMaxUserId();
            instance.Delete(userId);
        }

        [Test]
        /// 
        /// 删除用户
        /// 
        /// 用户实体
        /// 
        public void Delete()
        {
            int userId = instance.GetMaxUserId();
            UserInfo info = instance.Read(userId);
            Console.WriteLine("MaxUserId=" + userId);
            instance.Delete(info);
        }
    }
}