5、ASP.NET MVC入门到精通——NHibernate代码映射

本系列目录:ASP.NET MVC4入门到精通系列目录汇总

上一篇NHibernate学习笔记—使用 NHibernate构建一个ASP.NET MVC应用程序

使用的是xml进行orm映射,那么这一篇就来讲下代码映射。

新建一个抽象的数据化持久基类AbstractNHibernateDao.cs

    /// 
    /// 数据持久化基本
    /// 
    /// 要持久化的数据类型
    /// ID字段的数据类型
    public abstract class AbstractNHibernateDao : IDao
    {
        private const string APPSETTING_NAME = "sessionPath";
                
        /// 指定Session工厂的配置文件
        protected AbstractNHibernateDao(string sessionFactoryConfigPath) {
            if (string.IsNullOrEmpty(sessionFactoryConfigPath))
            {
                sessionFactoryConfigPath = "NHibernate.config";
            }
            //如果路径中包含 :(盘符) 符号,则证明传入的是一个绝对路径,可直接使用。
            //否则就是相对路径,在WEB环境中,用Server.MapPath转换成绝对路径,在App环境中,则加上当前运行目录
            if (sessionFactoryConfigPath.Contains(":"))
                SessionFactoryConfigPath = sessionFactoryConfigPath;
            else if (System.Web.HttpContext.Current != null)
                SessionFactoryConfigPath = System.Web.HttpContext.Current.Server.MapPath("~/"+sessionFactoryConfigPath);
            else
                SessionFactoryConfigPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, sessionFactoryConfigPath);
        }

        /// 
        /// 初始化AbstractNHibernateDao类,默认使用config文件Appsetting中 sessionPath所指定的文件进行初始化
        /// 
        protected AbstractNHibernateDao()
            : this(ConfigurationManager.AppSettings[APPSETTING_NAME])
        {
        }

        /// 
        /// 根据ID从数据库获取一个类型为T的实例
        /// 
        public T GetById(TId id, bool shouldLock)
        {
            T entity;

            if (shouldLock)
            {
                entity = NHibernateSession.Get(id, LockMode.Upgrade);
            }
            else
            {
                entity = NHibernateSession.Get(id);
            }

            return entity;
        }

        /// 
        /// 根据ID从数据库获取一个类型为T的实例
        /// 
        public T GetById(TId id)
        {
            return GetById(id, false);
        }

        /// 
        /// 获取所有的类型为T的对象
        /// 
        public IList GetAll() {
            return GetByCriteria();
        }

        /// 
        /// 根据给定的  来查询结果
        /// 如果没有传入 , 效果与 一致.
        /// 
        public IList GetByCriteria(params ICriterion[] criterion) {
            ICriteria criteria = NHibernateSession.CreateCriteria(persitentType);

            foreach (ICriterion criterium in criterion) {
                criteria.Add(criterium);
            }            
            criteria.AddOrder(new Order("ID", false));
            return criteria.List();
        }

        /// 
        /// 根据exampleInstance的属性值来查找对象,返回与其值一样的对象对表。
        /// exampleInstance中值为0或NULL的属性将不做为查找条件
        /// 
        /// 参考对象
        /// 要排除的查询条件属性名
        /// 
        public IList GetByExample(T exampleInstance, params string[] propertiesToExclude)
        {
            ICriteria criteria = NHibernateSession.CreateCriteria(exampleInstance.GetType());
            Example example = Example.Create(exampleInstance);

            foreach (string propertyToExclude in propertiesToExclude) {
                example.ExcludeProperty(propertyToExclude);
            }
            example.ExcludeNone();
            example.ExcludeNulls();
            example.ExcludeZeroes();
            criteria.Add(example);
            criteria.AddOrder(new Order("ID", false));
            return criteria.List();
        }

        public IPageOfList GetByExample(T exampleInstance, int pageIndex, int pageSize, params string[] propertiesToExclude)
        {
            ICriteria criteria = NHibernateSession.CreateCriteria(persitentType);
            Example example = Example.Create(exampleInstance);

            foreach (string propertyToExclude in propertiesToExclude) {
                example.ExcludeProperty(propertyToExclude);
            }
            example.ExcludeNone();
            example.ExcludeNulls();
            example.ExcludeZeroes();
            
            int recordTotal = Convert.ToInt32((criteria.Clone() as ICriteria).SetProjection(Projections.Count("ID")).UniqueResult());

            criteria.AddOrder(new Order("ID", false));
            criteria.Add(example).SetFirstResult(pageIndex*pageSize).SetMaxResults(pageSize);

            return new PageOfList(criteria.List(), pageIndex, pageSize, recordTotal);
        }

        /// 
        /// 使用来返回一个唯一的结果,如果结果不唯一会抛出异常
        /// 
        /// 
        public T GetUniqueByExample(T exampleInstance, params string[] propertiesToExclude) {
            IList foundList = GetByExample(exampleInstance, propertiesToExclude);

            if (foundList.Count > 1) {
                throw new NonUniqueResultException(foundList.Count);
            }

            if (foundList.Count > 0) {
                return foundList[0];
            }
            else {
                return default(T);
            }
        }

        /// 
        /// 将指定的对象保存到数据库,并立限提交,并返回更新后的ID
        /// See http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-id-assigned.
        /// 
        public T Save(T entity) {
            NHibernateSession.Save(entity);
            NHibernateSession.Flush();
            return entity;
        }

        /// 
        /// 将指定的对象保存或更新到数据库,并返回更新后的ID
        /// 
        public T SaveOrUpdate(T entity)
        {
            NHibernateSession.SaveOrUpdate(entity);
            NHibernateSession.Flush();
            return entity;
        }

        /// 
        /// 从数据库中删除指定的对象
        /// 
        public void Delete(T entity)
        {
            NHibernateSession.Delete(entity);
            NHibernateSession.Flush();
        }

        public DbTransaction BeginTransaction()
        {
            ITransaction tran = NHibernateSession.BeginTransaction();// NHibernateSessionManager.Instance.BeginTransactionOn(SessionFactoryConfigPath);
            return new DbTransaction(tran);
        }

        /// 
        /// 提交所有的事务对象,并Flush到数据库
        /// 
        public void CommitChanges() {
            if (NHibernateSessionManager.Instance.HasOpenTransactionOn(SessionFactoryConfigPath)) {
                NHibernateSessionManager.Instance.CommitTransactionOn(SessionFactoryConfigPath);
            }
            else {
                // 如果不是事务模式,就直接调用Flush来更新                
                NHibernateSession.Flush();
            }
        }

        /// 
        /// 返回对应的Session.
        /// 
        protected ISession NHibernateSession {
            get {
                return NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath);
            }
        }

        /// 
        /// 数据类型
        /// 
        private Type persitentType = typeof(T);
        
        /// 
        /// Session配置文件路径
        /// 
        protected readonly string SessionFactoryConfigPath;

        public virtual IPageOfList GetByFilter(ParameterFilter filter)
        {
            string sql = " from " + typeof(T).Name + " a where 1=1 ";
            if (filter.HasQueryString)
                sql = filter.ToHql();
            else
                sql += filter.ToHql();

            var paras = filter.GetParameters();
            var countQuery = NHibernateSession.CreateQuery("select count(*) " + sql);
            var query = NHibernateSession.CreateQuery("select a " + sql + filter.GetOrderString());

            foreach (var key in paras.Keys)
            {
                countQuery.SetParameter(key, paras[key]);
                query.SetParameter(key, paras[key]);
            }

            int pageIndex = filter.PageIndex;
            int pageSize = filter.PageSize;
            long recodTotal = Convert.ToInt64(countQuery.UniqueResult());
            var list = query.SetFirstResult(pageIndex * pageSize).SetMaxResults(pageSize).List();
            return new PageOfList(list, pageIndex, pageSize, recodTotal);
        }
    }
View Code

新建一个控制器Customer

    /// 
    /// 客户控制器
    /// 
    [Authorize]
    public class CustomerController : Controller
    {

        #region 客户管理主页
        public ActionResult Index()
        {
            return View();
        }

        /// 
        /// 客户列表
        /// 
        /// 
        /// 
        [HttpPost]
        public JsonResult List(CustomerFilter filter)
        {
            filter.PageSize = int.MaxValue;
            var dataSource = CustomerInfo.GetByFilter(filter);

            List queryData = dataSource.ToList();

            var data = queryData.Select(u => new
            {
                ID = u.ID,
                CusCode = u.CusCode,
                CusName = u.CusName,
                BusssinessType = u.BusssinessType.GetDescription(false),
                Balance = u.Balance,
                CreditAmount = u.CreditAmount,
                Status = u.Status.GetDescription(false),
                Country = u.Country,
                CompanyName = u.CompanyName,
                Delivery = GetDeliveryList(u.ExpressCurInfoBy),
                Cus_Level = u.CusLevel.ToChinese()
            });

            //构造成Json的格式传递
            var result = new { iTotalRecords = queryData.Count, iTotalDisplayRecords = 10, data = data };
            return Json(result, JsonRequestBehavior.AllowGet);
        }
}

新建实体类CustomerInfo.cs

    /// 
    /// 客户信息
    /// 
    public class CustomerInfo : DomainObjectint, ICustomerInfoRepository>
    {
        #region property
        /// 
        /// 客户代码
        /// 
        [Required(ErrorMessage = "客户代码不能为空!")]
        [StringLength(30, MinimumLength = 0, ErrorMessage = "客户代码最大长度为30个字符")]
        public virtual string CusCode { get; set; }
        /// 
        /// 客户名称
        /// 
        [Required(ErrorMessage = "客户名称不能为空!")]
        [StringLength(30, MinimumLength = 0, ErrorMessage = "客户名称最大长度为30个字符")]
        public virtual string CusName { get; set; }
        /// 
        /// 客户业务类型
        /// 
        public virtual Busssiness BusssinessType { get; set; }
        /// 
        /// 手机
        /// 
        public virtual string Phone { get; set; }
        /// 
        /// 电话
        /// 
        public virtual string Tel { get; set; }
        /// 
        /// 邮箱
        /// 
        [RegularExpression(@"^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$", ErrorMessage="邮箱格式不正确!")]
        public virtual string Email { get; set; }
        /// 
        /// 传真
        /// 
        public virtual string Fax { get; set; }
        /// 
        /// 国家
        /// 
        public virtual string Country { get; set; }
        /// 
        /// 地址
        /// 
        public virtual string Address { get; set; }
        /// 
        /// 公司名称
        /// 
        public virtual string CompanyName { get; set; }
        /// 
        /// 金额
        /// 
        public virtual decimal Balance { get; set; }
        /// 
        /// 信用额度
        /// 
        public virtual decimal CreditAmount { get; set; }
        /// 
        /// 状态
        /// 
        public virtual CustomerStatus Status { get; set; }
        /// 
        /// 快件收货商信息
        /// 
        public virtual IList ExpressCurInfoBy { get; set; }
        /// 
        /// 客户等级
        /// 
        public virtual CustomerLevel CusLevel { get; set; }
        /// 
        /// 级别生效日期
        /// 
        [Required(ErrorMessage = "级别生效日期不能为空!")]
        public virtual DateTime LevelEffectDate { get; set; }
        /// 
        /// 客户上一次级别
        /// 
        public virtual CustomerLevel CusPreLevel{get;set;}

        #endregion

        #region common method
        /// 
        /// 分页获取数据
        /// 
        /// 
        /// 
        public static IPageOfList GetByFilter(CustomerFilter filter)
        {
            return Dao.GetByFilter(filter);
        }
#endregion
    }
    ///
    /// 客户业务类型
    ///

    public enum Busssiness
    {
        ///
        /// 快件
        ///

        [Description("快件")]
        ExpressDelivery = 0,
    }
    ///
    /// 客户状态
    ///

    public enum CustomerStatus
    {
        ///
        /// 启用
        ///

        [Description("启用")]
        Enable = 0,
        ///
        /// 禁用
        ///

        [Description("禁用")]
        Disabled = 1,
    }
    ///
    /// 客户等级
    ///

    public enum CustomerLevel
    {
        [Description("1万件以下")]
        One=0,
        [Description("1万-3万件")]
        Two=1,
        [Description("3万件以上")]
        Three=2
    }

新建ICustomerInfoRepository.cs

    public interface ICustomerInfoRepository : IDaoint>
    {
    }

新建CustomerInfoRepository.cs

    public class CustomerInfoRepository : AbstractNHibernateDaoint>, ICustomerInfoRepository
    {
    }

使用Unity将ICustomerInfoRepository和CustomerInfoRepository进行注入。具体请参考我的另一篇博文:IOC框架之Unity

添加抽象类ParameterFilter.cs 查询过滤基类

 public abstract class ParameterFilter
    {
        public ParameterFilter()
        {
            HasQueryString = false;
            PageSize = 10;
        }

        public string OrderBy { get;set; }

        public abstract string ToHql();

        public override string ToString()
        {
            return ToHql();
        }

        public abstract Dictionary<string, object> GetParameters();

        public string GetOrderString()
        {
            if (OrderBy.HasValue())
                return " Order By " + OrderBy;
            return String.Empty;
        }

        protected string GetLike(string value)
        {
            return "%" + value + "%";
        }

        public int PageIndex { get; set; }

        public int PageSize { get; set; }

        /// 
        /// 标识此构造器是包含全部查询语句。
        /// 若为 False,则ToHql() 只需要构造条件查询,系统会自动在前面加上" from " + typeof(T).Name + " a where 1=1 "
        /// 若为 True, ToHql() 需要返回 连form在类的完整Hql语句
        /// 
        public bool HasQueryString { get; set; }

        protected static bool HasValue(string str)
        {
            return str.HasValue();
        }

        public static bool HasValue(System.Nullable value) where T:struct
        {
            return value.HasValue;
        }       
        
    }
View Code

添加查询过滤子类CustomerFilter.cs

    public class CustomerFilter : ParameterFilter
    {
        /// 
        /// 客户代码
        /// 
        public virtual string CusCode { get; set; }
        /// 
        /// 客户名称
        /// 
        public virtual string CusName { get; set; }

        /// 
        /// 生产NHQL查询语句
        /// 
        /// 
        public override string ToHql()
        {
            string hql = "";
            if (!string.IsNullOrEmpty(CusCode))
            {
                hql += " and Cus_Code =:CusCode ";
            }
            if (!string.IsNullOrEmpty(CusName))
            {
                hql += " and Cus_Name like:CusName ";
            }

            return hql;
        }

        /// 
        /// 构造查询参数
        /// 
        /// 
        public override Dictionary<string, object> GetParameters()
        {
            var result = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(CusCode))
            {
                result["CusCode"] = CusCode.Trim();
            }
            if (!string.IsNullOrEmpty(CusName))
            {
                result["CusName"] = string.Format("{0}%", CusName.Trim());
            }
            return result;
        }
    }
View Code

新建代码映射类CustomerInfoMap

    /// 
    /// 客户信息映射
    /// 
    public class CustomerInfoMap : ClassMapping
    {
        public CustomerInfoMap()
        {
            Table("CustomerInfo");  //表名
            Id(p => p.ID, m => { m.Generator(Generators.Identity); m.Column("ID"); });  //自增长主键
            Property(p => p.CusCode, m => m.Column("Cus_Code"));  //表字段Cus_Code
            Property(p => p.CusName, m => m.Column("Cus_Name")); //表字段Cus_Name
            Property(p => p.BusssinessType, m => { m.Type>(); });
            Property(p => p.Phone);
            Property(p => p.Tel);
            Property(p => p.Email);
            Property(p => p.Fax);
            Property(p => p.Country);
            Property(p => p.Address);
            Property(p => p.CompanyName);
            Property(p => p.Balance);
            Property(p => p.CreditAmount);
            Property(p => p.Status, x => x.Type>()); //枚举
            //Bag Column传的值是从表的外键
            Bag(p => p.ExpressCurInfoBy, m => { m.Key(k => k.Column("CusID")); m.Cascade(Cascade.All); }, rel => rel.OneToMany());
            Property(p => p.CusLevel, x => { x.Type>(); x.Column("Cus_Level"); });
            Property(p => p.CusPreLevel, x => { x.Type>(); x.Column("Cus_PreLevel"); });
            Property(p => p.LevelEffectDate);
        }
    }

界面UI参考ASP.NET MVC搭建项目后台UI框架—1、后台主框架

5、ASP.NET MVC入门到精通——NHibernate代码映射_第1张图片

你可能感兴趣的:(5、ASP.NET MVC入门到精通——NHibernate代码映射)