本系列目录:ASP.NET MVC4入门到精通系列目录汇总
上一篇NHibernate学习笔记—使用 NHibernate构建一个ASP.NET MVC应用程序
使用的是xml进行orm映射,那么这一篇就来讲下代码映射。
新建一个抽象的数据化持久基类AbstractNHibernateDao.cs
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
/// <summary>
/// 数据持久化基本
/// </summary>
/// <typeparam name="T">要持久化的数据类型</typeparam>
/// <typeparam name="TID">ID字段的数据类型</typeparam>
public abstract class AbstractNHibernateDao<T, TId> : IDao<T, TId>
{
private const string APPSETTING_NAME = "sessionPath";
/// <param name="sessionFactoryConfigPath">指定Session工厂的配置文件</param>
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);
}
/// <summary>
/// 初始化AbstractNHibernateDao类,默认使用config文件Appsetting中 sessionPath所指定的文件进行初始化
/// </summary>
protected AbstractNHibernateDao()
: this(ConfigurationManager.AppSettings[APPSETTING_NAME])
{
}
/// <summary>
/// 根据ID从数据库获取一个类型为T的实例
/// </summary>
public T GetById(TId id, bool shouldLock)
{
T entity;
if (shouldLock)
{
entity = NHibernateSession.Get<T>(id, LockMode.Upgrade);
}
else
{
entity = NHibernateSession.Get<T>(id);
}
return entity;
}
/// <summary>
/// 根据ID从数据库获取一个类型为T的实例
/// </summary>
public T GetById(TId id)
{
return GetById(id, false);
}
/// <summary>
/// 获取所有的类型为T的对象
/// </summary>
public IList<T> GetAll() {
return GetByCriteria();
}
/// <summary>
/// 根据给定的 <see cref="ICriterion" /> 来查询结果
/// 如果没有传入 <see cref="ICriterion" />, 效果与 <see cref="GetAll" />一致.
/// </summary>
public IList<T> 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<T>();
}
/// <summary>
/// 根据exampleInstance的属性值来查找对象,返回与其值一样的对象对表。
/// exampleInstance中值为0或NULL的属性将不做为查找条件
/// </summary>
/// <param name="exampleInstance">参考对象</param>
/// <param name="propertiesToExclude">要排除的查询条件属性名</param>
/// <returns></returns>
public IList<T> 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<T>();
}
public IPageOfList<T> 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<T>(criteria.List<T>(), pageIndex, pageSize, recordTotal);
}
/// <summary>
/// 使用<see cref="GetByExample"/>来返回一个唯一的结果,如果结果不唯一会抛出异常
/// </summary>
/// <exception cref="NonUniqueResultException" />
public T GetUniqueByExample(T exampleInstance, params string[] propertiesToExclude) {
IList<T> foundList = GetByExample(exampleInstance, propertiesToExclude);
if (foundList.Count > 1) {
throw new NonUniqueResultException(foundList.Count);
}
if (foundList.Count > 0) {
return foundList[0];
}
else {
return default(T);
}
}
/// <summary>
/// 将指定的对象保存到数据库,并立限提交,并返回更新后的ID
/// See http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-id-assigned.
/// </summary>
public T Save(T entity) {
NHibernateSession.Save(entity);
NHibernateSession.Flush();
return entity;
}
/// <summary>
/// 将指定的对象保存或更新到数据库,并返回更新后的ID
/// </summary>
public T SaveOrUpdate(T entity)
{
NHibernateSession.SaveOrUpdate(entity);
NHibernateSession.Flush();
return entity;
}
/// <summary>
/// 从数据库中删除指定的对象
/// </summary>
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);
}
/// <summary>
/// 提交所有的事务对象,并Flush到数据库
/// </summary>
public void CommitChanges() {
if (NHibernateSessionManager.Instance.HasOpenTransactionOn(SessionFactoryConfigPath)) {
NHibernateSessionManager.Instance.CommitTransactionOn(SessionFactoryConfigPath);
}
else {
// 如果不是事务模式,就直接调用Flush来更新
NHibernateSession.Flush();
}
}
/// <summary>
/// 返回对应的Session.
/// </summary>
protected ISession NHibernateSession {
get {
return NHibernateSessionManager.Instance.GetSessionFrom(SessionFactoryConfigPath);
}
}
/// <summary>
/// 数据类型
/// </summary>
private Type persitentType = typeof(T);
/// <summary>
/// Session配置文件路径
/// </summary>
protected readonly string SessionFactoryConfigPath;
public virtual IPageOfList<T> 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<T>();
return new PageOfList<T>(list, pageIndex, pageSize, recodTotal);
}
}
新建一个控制器Customer
/// <summary>
/// 客户控制器
/// </summary>
[Authorize]
public class CustomerController : Controller
{
#region 客户管理主页
public ActionResult Index()
{
return View();
}
/// <summary>
/// 客户列表
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
[HttpPost]
public JsonResult List(CustomerFilter filter)
{
filter.PageSize = int.MaxValue;
var dataSource = CustomerInfo.GetByFilter(filter);
List<CustomerInfo> 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
/// <summary>
/// 客户信息
/// </summary>
public class CustomerInfo : DomainObject<CustomerInfo, int, ICustomerInfoRepository>
{
#region property
/// <summary>
/// 客户代码
/// </summary>
[Required(ErrorMessage = "客户代码不能为空!")]
[StringLength(30, MinimumLength = 0, ErrorMessage = "客户代码最大长度为30个字符")]
public virtual string CusCode { get; set; }
/// <summary>
/// 客户名称
/// </summary>
[Required(ErrorMessage = "客户名称不能为空!")]
[StringLength(30, MinimumLength = 0, ErrorMessage = "客户名称最大长度为30个字符")]
public virtual string CusName { get; set; }
/// <summary>
/// 客户业务类型
/// </summary>
public virtual Busssiness BusssinessType { get; set; }
/// <summary>
/// 手机
/// </summary>
public virtual string Phone { get; set; }
/// <summary>
/// 电话
/// </summary>
public virtual string Tel { get; set; }
/// <summary>
/// 邮箱
/// </summary>
[RegularExpression(@"^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$", ErrorMessage="邮箱格式不正确!")]
public virtual string Email { get; set; }
/// <summary>
/// 传真
/// </summary>
public virtual string Fax { get; set; }
/// <summary>
/// 国家
/// </summary>
public virtual string Country { get; set; }
/// <summary>
/// 地址
/// </summary>
public virtual string Address { get; set; }
/// <summary>
/// 公司名称
/// </summary>
public virtual string CompanyName { get; set; }
/// <summary>
/// 金额
/// </summary>
public virtual decimal Balance { get; set; }
/// <summary>
/// 信用额度
/// </summary>
public virtual decimal CreditAmount { get; set; }
/// <summary>
/// 状态
/// </summary>
public virtual CustomerStatus Status { get; set; }
/// <summary>
/// 快件收货商信息
/// </summary>
public virtual IList<ExpressCurInfo> ExpressCurInfoBy { get; set; }
/// <summary>
/// 客户等级
/// </summary>
public virtual CustomerLevel CusLevel { get; set; }
/// <summary>
/// 级别生效日期
/// </summary>
[Required(ErrorMessage = "级别生效日期不能为空!")]
public virtual DateTime LevelEffectDate { get; set; }
/// <summary>
/// 客户上一次级别
/// </summary>
public virtual CustomerLevel CusPreLevel{get;set;}
#endregion
#region common method
/// <summary>
/// 分页获取数据
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public static IPageOfList<CustomerInfo> GetByFilter(CustomerFilter filter)
{
return Dao.GetByFilter(filter);
}
#endregion
}
/// <summary>
/// 客户业务类型
/// </summary>
public enum Busssiness
{
/// <summary>
/// 快件
/// </summary>
[Description("快件")]
ExpressDelivery = 0,
}
/// <summary>
/// 客户状态
/// </summary>
public enum CustomerStatus
{
/// <summary>
/// 启用
/// </summary>
[Description("启用")]
Enable = 0,
/// <summary>
/// 禁用
/// </summary>
[Description("禁用")]
Disabled = 1,
}
/// <summary>
/// 客户等级
/// </summary>
public enum CustomerLevel
{
[Description("1万件以下")]
One=0,
[Description("1万-3万件")]
Two=1,
[Description("3万件以上")]
Three=2
}
新建ICustomerInfoRepository.cs
public interface ICustomerInfoRepository : IDao<CustomerInfo, int>
{
}
新建CustomerInfoRepository.cs
public class CustomerInfoRepository : AbstractNHibernateDao<CustomerInfo, int>, ICustomerInfoRepository
{
}
使用Unity将ICustomerInfoRepository和CustomerInfoRepository进行注入。具体请参考我的另一篇博文:IOC框架之Unity
添加抽象类ParameterFilter.cs 查询过滤基类
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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; }
/// <summary>
/// 标识此构造器是包含全部查询语句。
/// 若为 False,则ToHql() 只需要构造条件查询,系统会自动在前面加上<code>" from " + typeof(T).Name + " a where 1=1 "</code>
/// 若为 True, ToHql() 需要返回 连form在类的完整Hql语句
/// </summary>
public bool HasQueryString { get; set; }
protected static bool HasValue(string str)
{
return str.HasValue();
}
public static bool HasValue<T>(System.Nullable<T> value) where T:struct
{
return value.HasValue;
}
}
添加查询过滤子类CustomerFilter.cs
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public class CustomerFilter : ParameterFilter
{
/// <summary>
/// 客户代码
/// </summary>
public virtual string CusCode { get; set; }
/// <summary>
/// 客户名称
/// </summary>
public virtual string CusName { get; set; }
/// <summary>
/// 生产NHQL查询语句
/// </summary>
/// <returns></returns>
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;
}
/// <summary>
/// 构造查询参数
/// </summary>
/// <returns></returns>
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;
}
}
新建代码映射类CustomerInfoMap
/// <summary>
/// 客户信息映射
/// </summary>
public class CustomerInfoMap : ClassMapping<CustomerInfo>
{
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<NHibernate.Type.EnumType<Busssiness>>(); });
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<NHibernate.Type.EnumType<CustomerStatus>>()); //枚举
//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<NHibernate.Type.EnumType<CustomerLevel>>(); x.Column("Cus_Level"); });
Property(p => p.CusPreLevel, x => { x.Type<NHibernate.Type.EnumType<CustomerLevel>>(); x.Column("Cus_PreLevel"); });
Property(p => p.LevelEffectDate);
}
}
界面UI参考ASP.NET MVC搭建项目后台UI框架—1、后台主框架