码迷,mamicode.com
首页 > 其他好文 > 详细

框架实例应用例子

时间:2014-10-23 12:08:05      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   os   ar   java   for   

首先是实体类,继承ORM基类

//--------------------------------------------------------------------------------
// 文件描述:管理员信息实体
// 文件作者:品浩
// 创建日期:2013-12-12
// 修改记录: 
//--------------------------------------------------------------------------------
using System;
using System.Data;
using lph.Foundation;
using lph.FrameWork;

namespace lph.General.Admin.Model
{
    [Table("Admin")]
    public class AdminInfo : Info, IAdministratorInfo
    {
        [Column("AdminName", SqlDbType.VarChar)]
        /// <summary>
        /// 管理员名称 
        /// </summary>
        public string AdminName { get; set; }

        [Column("AdminPassword", SqlDbType.VarChar)]
        /// <summary>
        /// 管理员密码 
        /// </summary>
        public string AdminPassword { get; set; }

        [Column("UserName", SqlDbType.VarChar)]
        /// <summary>
        /// 关联前台用户名
        /// </summary>
        public string UserName { get; set; }

        [Column("RndPassword", SqlDbType.VarChar)]
        /// <summary>
        /// 随机密码
        /// </summary>
        public string RndPassword { get; set; }

        [Column("EnableMultiLogin", SqlDbType.Bit)]
        /// <summary>
        /// 是否可以在多处登录 
        /// </summary>
        public bool EnableMultiLogin { get; set; }

        [Column("EnableModifyPassword", SqlDbType.Bit)]
        /// <summary>
        /// 是否允许修改自己的密码 
        /// </summary>
        public bool EnableModifyPassword { get; set; }

        [Column("Status", SqlDbType.Bit)]
        /// <summary>
        /// 帐号状态(1启用,0禁用) 
        /// </summary>
        public bool Status { get; set; }

        [Column("LoginTimes", SqlDbType.Int)]
        /// <summary>
        /// 登录次数 
        /// </summary>
        public int LoginTimes { get; set; }

        [Column("LoginErrorTimes", SqlDbType.Int)]
        /// <summary>
        /// 登录错误次数 
        /// </summary>
        public int LoginErrorTimes { get; set; }

        [Column("LoginErrorTimes_Today", SqlDbType.Int)]
        /// <summary>
        /// 今天登录错误次数 
        /// </summary>
        public int LoginErrorTimes_Today { get; set; }

        [Column("LastLoginIP", SqlDbType.VarChar)]
        /// <summary>
        /// 最后登录IP 
        /// </summary>
        public string LastLoginIP { get; set; }

        [Column("LastLoginTime", SqlDbType.DateTime)]
        /// <summary>
        /// 最后登录时间 
        /// </summary>
        public DateTime? LastLoginTime { get; set; }

        [Column("LastModifyPasswordTime", SqlDbType.DateTime)]
        /// <summary>
        /// 最后修改密码时间 
        /// </summary>
        public DateTime? LastModifyPasswordTime { get; set; }

        [Column("CreatTime", SqlDbType.DateTime)]
        /// <summary>
        /// 创建时间 
        /// </summary>
        public DateTime? CreatTime { get; set; }

        [Column("CreatPerson", SqlDbType.VarChar)]
        /// <summary>
        /// 创建人 
        /// </summary>
        public string CreatPerson { get; set; }

    }
}

 

 

然后只放出基类的一部分(基类是组装性质的)

1

//--------------------------------------------------------------------------------
// 文件描述:基类的字段、属性、构造函数
// 文件作者:品浩
// 创建日期:2013-11-01
// 修改记录: 
//--------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Script.Serialization;
using System.Data;
namespace lph.FrameWork
{
    /// <summary>
    /// 属性不被序列化--加[ScriptIgnore]特性,请记住!
    /// </summary>
    public partial class Info
    {
        /// <summary>
        /// 保存了所有实体的信息字典集合
        /// </summary>
        private static IDictionary<string, object> entityList = new Dictionary<string, object>();

        /// <summary>
        /// 本实体信息
        /// </summary>
        [ScriptIgnore]
        public Entity_Info entity;

        /// <summary>
        /// 插入语句模板
        /// </summary>
        private string insert_template = "insert into {0}{1};SELECT @Identity =@@Identity;";

        /// <summary>
        /// 更新语句模板
        /// </summary>
        private string update_template = "update {0} set {1}";



        /// <summary>
        /// 构造实体类需要的数据映射关系
        /// </summary>
        public Info()
        {
            Type t = this.GetType();

            if (entityList.ContainsKey(t.Name))
            {
                entity = entityList[t.Name] as Entity_Info;
            }
            else
            {
                entity = new Entity_Info();//用于保存实体信息,减少反射从而提高性能

                entity.type = t;//保存实体类型

                entity.info_table_name = GetTable(this).TableName;//得到对象的表名

                entity.m_Property = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

                entity.ColumnList = GetObjecColumns(this);

                entity.info_table_fields = GetInfoFields();//得到字段列表

                entity.m_searchFields = entity.info_table_fields.Split(,);//得到搜索字段列表

                entity.insert_sql = string.Format(insert_template, entity.info_table_name, GetInsertSql());//赋值插入语句

                entity.update_sql = string.Format(update_template, entity.info_table_name, GetUpdateSql());//赋值更新语句

                //缓存,加入字典列表
                if (!entityList.ContainsKey(t.Name))
                {
                    entityList.Add(t.Name, entity);
                }
            }
        }

        //=======================================================================
        /// <summary>
        /// 用于记录更新随机值,处理高并发问题,只在读取信息的时候赋值并写入缓存,若更新的时候数值不相等即是已经被更改过
        /// </summary>
        [Ignore(true), ScriptIgnore]
        public string UpdateRandom { get; set; }

        /// <summary>
        /// 记录本次查询时总记录数
        /// </summary>
        [Ignore(true), ScriptIgnore]
        public int totalNumber { get; set; }

        /// <summary>
        /// 每个表的自增列ID
        /// </summary>
        [Column("ID", SqlDbType.Int), Ignore(true)]
        public virtual int ID { get; set; }
        //==============================================================================================================================
    }
}

2

using System;
//--------------------------------------------------------------------------------
// 文件描述:增删改查等公有方法(外部调用方法集合)
// 文件作者:品浩
// 创建日期:2013-11-01
// 修改记录: 
//--------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;
using System.Data.SqlClient;


namespace lph.FrameWork
{
    public partial class Info
    {

        /// <summary>
        /// 返回添加信息的结果集
        /// </summary>
        /// <returns></returns>
        public DBResult Add()
        {
            DBResult DalResult = new DBResult();
            try
            {
                Parameters parms = GetParameters();
                parms.AddOutParameter("@Identity", SqlDbType.Int, 0);

                int Identity = DBHelper.ExecuteOutput(entity.insert_sql, parms).ToInt32();

                if (Identity > 0)
                {
                    SiteCache.Max(SiteCacheKey.CK_MaxID_ + entity.info_table_name, Identity);
                    DalResult.result = Status.Success;
                    DalResult.IdentityID = Identity;
                }
                return DalResult;

            }
            catch (Exception ex)
            {
                DalResult.PromptMessage = ex.Message;
                DalResult.result = Status.Other;
                return DalResult;
            }
        }

        /// <summary>
        /// 返回更新的结果集
        /// </summary>
        /// <returns></returns>
        public DBResult Update()
        {
            string filter = "ID=" + this.ID;
            return Update(filter);
        }

        /// <summary>
        /// 返回更新的结果集, 此版本根据(where)条件,如参数"ID=1"
        /// </summary>
        /// <returns></returns>
        public DBResult Update(string filter)
        {
            DBResult DalResult = new DBResult();
            bool result = false;
            string randomStr = SiteCacheKey.Null;
            try
            {
                Parameters parms = GetParameters();
                string updateSql = entity.update_sql + " where " + filter;


                if (SiteCache.Get(SiteCacheKey.CK_Random_ + entity.info_table_name + this.ID) != null)
                {
                    randomStr = SiteCache.Get(SiteCacheKey.CK_Random_ + entity.info_table_name + this.ID).ToString();
                }
                if (randomStr == this.UpdateRandom | randomStr == SiteCacheKey.Null)
                {
                    result = DBHelper.ExecuteSql(updateSql, parms);
                    if (result)
                    {
                        lock (entity.lock_update)
                        {
                            SiteCache.Max(SiteCacheKey.CK_Random_ + entity.info_table_name + this.ID, RandomHelper.GetRandomString(20));
                        }
                    }
                }
                else
                {
                    DalResult.PromptMessage = "信息已被前一线程更新,为了安全性,请重新操作";
                    DalResult.result = Status.Other;
                    return DalResult;
                }


                if (result)
                {
                    DalResult.result = Status.Success;
                }
                return DalResult;
            }
            catch (Exception ex)
            {
                DalResult.PromptMessage = ex.Message;
                DalResult.result = Status.Other;
                return DalResult;
            }
        }

        /// <summary>
        /// 根据id删除指定信息,格式1 id:1 格式2 id:1,2,3
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(string id)
        {
            return DBHelper.ExecuteSql("DELETE FROM " + entity.info_table_name + " WHERE ID IN ( " + DBHelper.ToValidId(id) + " )");
        }

        /// <summary>
        /// 删除自己
        /// </summary>
        /// <returns></returns>
        public bool Delete()
        {
            return DBHelper.ExecuteSql("DELETE FROM " + entity.info_table_name + " WHERE ID=" + this.ID);
        }

        /// <summary>
        ///  根据条件删除信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public bool DeleteByFilter(string filter)
        {
            return DBHelper.ExecuteSql("DELETE FROM " + entity.info_table_name + " WHERE " + filter);
        }

        /// <summary>
        /// 根据id获取指定信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetInfoById<T>(int id) where T : Info, new()
        {
            T obj = null;
            SqlDataReader result = DBHelper.ExecuteReader("SELECT * FROM " + entity.info_table_name + " with (nolock) WHERE ID = @ID", new Parameters("@ID", SqlDbType.Int, id));

            if (result.Read())
            {
                obj = InfoFromRdr<T>(new NullableDataReader(result));
            }

            return obj;
        }

        /// <summary>
        /// 根据指定列与值获得信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="column"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public T GetInfoByFilter<T>(string column, string value) where T : Info, new()
        {
            T obj = null;
            SqlDataReader result = DBHelper.ExecuteReader("SELECT * FROM " + entity.info_table_name + " with (nolock)  WHERE " + column + " = @" + column, new Parameters("@" + column, SqlDbType.VarChar, value));

            if (result.Read())
            {
                obj = InfoFromRdr<T>(new NullableDataReader(result));
            }

            return obj;
        }

        /// <summary>
        /// 根据sql获取指定信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <returns></returns>
        public T GetInfoBySql<T>(string sql) where T : Info, new()
        {
            T obj = null;
            using (SqlDataReader rdr = DBHelper.ExecuteReader(sql))
            {
                if (rdr.Read())
                {
                    obj = InfoFromRdr<T>(new NullableDataReader(rdr));
                }
            }
            return obj;
        }

        /// <summary>
        /// 判断指定字段的值是否存在
        /// </summary>
        public bool IsExist<T>(string column, string value) where T : Info, new()
        {
            bool result = false;

            string strSql = "SELECT COUNT(*) FROM {0}  with (nolock) WHERE {1} =‘{2}‘";
            value = DBHelper.FilterBadChar(value);
            result = DBHelper.Exists(string.Format(strSql, entity.info_table_name, column, value));

            return result;
        }
        public bool IsExist<T>(string column, string value, string oldID) where T : Info, new()
        {
            bool result = false;
            value = DBHelper.FilterBadChar(value);
            string strSql = "SELECT COUNT(*) FROM {0}  with (nolock) WHERE {1} =‘{2}‘ and ID!=" + oldID;

            result = DBHelper.Exists(string.Format(strSql, entity.info_table_name, column, value));

            return result;
        }


        /// <summary>
        /// 直接执行SQL语句
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public bool ExecuteSql(string strSql)
        {
            return DBHelper.ExecuteSql(strSql);
        }

        /// <summary>
        /// 获取信息列表(根据开始行数,每页显示行数),totalNumber为表的总行数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="startRowIndexId"></param>
        /// <param name="maxNumberRows"></param>
        /// <returns></returns>
        public IList<T> GetList<T>(int startRowIndexId, int maxNumberRows) where T : Info, new()
        {
            return GetList<T>(startRowIndexId, maxNumberRows, null);
        }

        /// <summary>
        /// 获取信息列表(根据开始行数,每页显示行数,条件)条件格式:Category = 1 或 Category like %x% 自由组合sql语句
        /// totalNumber为表的总行数
        /// </summary>
        /// <param name="startRowIndexId"></param>
        /// <param name="maxNumberRows"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public IList<T> GetList<T>(int startRowIndexId, int maxNumberRows, string filter) where T : Info, new()
        {

            ListParameters listParms = new ListParameters(startRowIndexId, maxNumberRows, entity.info_table_name, "*", "ID", (filter ?? string.Empty).ToString());
            return GetList<T>(listParms);
        }

        /// <summary>
        /// 获取信息列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listParameters"></param>
        /// <returns></returns>
        public IList<T> GetList<T>(ListParameters listParameters) where T : Info, new()
        {
            Parameters parms = new Parameters();
            string sorts = "DESC";
            if (listParameters.Sorts == Sorts.Asc)
            {
                sorts = "ASC";
            }
            parms.AddInParameter("@StartRows", SqlDbType.Int, listParameters.StartRows);//开始行数
            parms.AddInParameter("@PageSize", SqlDbType.Int, listParameters.PageSize);//每页显示多少行
            parms.AddInParameter("@SortColumn", SqlDbType.VarChar, listParameters.SortColumn);//排序列名
            parms.AddInParameter("@StrColumn", SqlDbType.VarChar, listParameters.StrColumn);//查询的列名,默认所有*
            parms.AddInParameter("@Sorts", SqlDbType.VarChar, sorts);//默认降序
            parms.AddInParameter("@Filter", SqlDbType.VarChar, listParameters.Filter);
            parms.AddInParameter("@TableName", SqlDbType.VarChar, listParameters.TableName);

            parms.AddOutParameter("@Total", SqlDbType.Int, 0);//输出参数,列表总数目
            SqlDataReader result = DBHelper.ExecuteReader("PR_Common_GetList", parms, CommandType.StoredProcedure);
            IList<T> List = new List<T>();

            while (result.Read())
            {
                List.Add(InfoFromRdr<T>(new NullableDataReader(result)));
            }

            this.totalNumber = List.Count;
            return List;
        }
        ///// <summary>
        ///// 获取信息列表(根据Sql语句)
        ///// totalNumber为查询结果的总行数
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="sql"></param>
        ///// <returns></returns>
        public IList<T> GetList<T>(string sql) where T : Info, new()
        {
            IList<T> List = new List<T>();
            Parameters parms = new Parameters();
            SqlDataReader result = DBHelper.ExecuteReader(sql, parms);
            while (result.Read())
            {
                List.Add(InfoFromRdr<T>(new NullableDataReader(result)));
            }

            this.totalNumber = List.Count.ToInt32();
            return List;
        }
        ///// <summary>
        ///// 获取最大ID
        ///// </summary>
        ///// <returns></returns>
        public int GetMaxId()
        {
            int maxID;

            if (SiteCache.Get(SiteCacheKey.CK_MaxID_ + entity.info_table_name) != null)
            {
                maxID = SiteCache.Get(SiteCacheKey.CK_MaxID_ + entity.info_table_name).ToInt32();
            }
            else
            {
                maxID = DBHelper.GetMaxID("ID", entity.info_table_name);
            }

            return maxID;
        }

        /// <summary>
        /// 返回最大记录数
        /// </summary>
        /// <returns></returns>
        public int GetCount()
        {
            return this.totalNumber;
        }

        #region 序列化与反序列化


        /// <summary>
        /// 序列化单个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Info"></param>
        /// <returns></returns>
        public static string SerializeInfo<T>(T Info) where T : Info, new()
        {
            return new JavaScriptSerializer().Serialize(Info);
        }

        /// <summary>
        /// 反序列化单个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="inputJson"></param>
        /// <returns></returns>
        public static T DeserializeToInfo<T>(string JsonStr) where T : Info, new()
        {
            return new JavaScriptSerializer().Deserialize<T>(JsonStr);
        }

        /// <summary>
        /// 序列化对象列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string SerializeInfoList<T>(IList<T> list) where T : Info, new()
        {
            var data = new { data = list };
            return new JavaScriptSerializer().Serialize(data);
        }


        /// <summary>
        /// 反序列化对象列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="JsonStr"></param>
        /// <returns></returns>
        public static List<T> DeserializeToInfoList<T>(string JsonStr) where T : Info, new()
        {
            Info_data<T> data = new Info_data<T>();
            data = new JavaScriptSerializer().Deserialize<Info_data<T>>(JsonStr);

            return (List<T>)data.data;
        }

        #endregion
    }



}

 

最核心的类只放出下面一个方法

 ///// <summary>
        ///// 读取数据库视图信息,转换为实体类
        ///// </summary>
        ///// <param name="rdr"></param>
        ///// <returns></returns>
        private T InfoFromRdr<T>(NullableDataReader rdr) where T : Info, new()
        {
            T Info = new T();
            foreach (ColumnInfo info in entity.ColumnList)
            {
                if (typeof(object).Equals(info.property.PropertyType) && !info.property.PropertyType.IsEnum && !string.IsNullOrEmpty(rdr[info.ColumnName].ToString()))
                {
                    TextReader textRead = new StringReader(rdr.GetString(info.ColumnName));
                    XmlSerializer serializer = new XmlSerializer(info.property.PropertyType);
                    info.property.SetValue(Info, serializer.Deserialize(textRead), null);
                    textRead.Close();
                }
                if (typeof(Int32).Equals(info.property.PropertyType) & !info.ColumnName.Compare("totalNumber"))
                {
                    info.property.SetValue(Info, rdr.GetInt32(info.ColumnName), null);
                }
                if (typeof(char).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetChar(info.ColumnName), null);
                }
                if (typeof(float).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetSingle(info.ColumnName), null);
                }
                if (typeof(DateTime).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetDateTime(info.ColumnName), null);
                }
                if (typeof(DateTime?).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetNullableDateTime(info.ColumnName), null);
                }
                if (typeof(int?).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetIntNullable(info.ColumnName), null);
                }
                if (typeof(byte).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetByte(info.ColumnName), null);
                }
                if (typeof(decimal).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetDecimal(info.ColumnName), null);
                }
                if (typeof(double).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetDouble(info.ColumnName), null);
                }
                if (typeof(bool).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetBoolean(info.ColumnName), null);
                }
                if (typeof(Guid).Equals(info.property.PropertyType))
                {
                    info.property.SetValue(Info, rdr.GetGuid(info.ColumnName), null);
                }
                if (info.property.PropertyType.IsEnum)
                {
                    info.property.SetValue(Info, Enum.Parse(info.property.PropertyType, rdr.GetInt32(info.ColumnName).ToString()), null);
                }
                if (typeof(string).Equals(info.property.PropertyType) & !info.ColumnName.Compare("updaterandom"))
                {
                    info.property.SetValue(Info, rdr.GetString(info.ColumnName) ?? string.Empty, null);
                }
                //更新库所需要的版本控制随机码
                if (info.ColumnName.Compare("updaterandom"))
                {
                    string randomStr = SiteCacheKey.Null;
                    if (SiteCache.Get(SiteCacheKey.CK_Random_ + entity.info_table_name + rdr["ID"].ToString()) != null)
                    {
                        randomStr = SiteCache.Get(SiteCacheKey.CK_Random_ + entity.info_table_name + rdr["ID"].ToString()).ToString();
                    }
                    info.property.SetValue(Info, randomStr, null);
                }


            }

            return Info;
        }

 

框架实例应用例子

标签:des   style   blog   color   io   os   ar   java   for   

原文地址:http://www.cnblogs.com/pinhao/p/4045219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!