利用反射和自定义特性实现基本数据存取操作自动获取

    /// <summary>
    /// 提供自定义表特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    class CustomTableAttribute:Attribute
    {
        private bool _isSubTable;
        string _parentTableName;
        string _tableName;
        public CustomTableAttribute(string tableName,bool isSubTable,string parentTableName)
        {
            this._isSubTable = isSubTable;
            this._tableName = tableName;
            this._parentTableName = parentTableName;
        }
        public CustomTableAttribute(string tableName)
            : this(tableName, false, null)
        {
        }
        public CustomTableAttribute(string tableName, bool isSubTable)
            : this(tableName, isSubTable, null)
        {

        }
        public string TableName { get { return this._tableName; } }
        public string ParentTableName { get { return this._parentTableName; } }
        public bool IsSubTable { get { return this._isSubTable; } }
    }
    /// <summary>
    /// 提供自定义列特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Field|AttributeTargets.Property)]
    class CustomColumnAttribute : Attribute
    {
        private string _columnName;
        private bool _isPk;
        private bool _isIdentity;
        public CustomColumnAttribute(string columnName, bool isPk, bool isIdentity)
        {
            this._columnName = columnName;
            this._isIdentity = isIdentity;
            this._isPk = isPk;
        }
        public CustomColumnAttribute(string columnName)
            : this(columnName, false, false)
        {
        }
        public CustomColumnAttribute(string columnName, bool isPk)
            : this(columnName, isPk,false)
        {
        }
        public string ColumnName { get { return this._columnName; } }
        public bool IsPK { get { return this._isPk; } }
        public bool IsIdentity { get { return this._isIdentity; } }
    } 

 

    /// <summary>
    /// 提供基础列抽象类型
    /// </summary>
    class BaseColumn
    {
        private Type _sysType;
        private DbType _dataType;
        private string _columnName;
        private bool _isPk;
        private bool _isIdentity;
        private object _value;
        public object Value { get { return this._value; } set { this._value = value; } }
        public bool IsPK { get { return this._isPk; } set { this._isPk = value; } }
        public bool IsIdentity { get { return this._isIdentity; } set { this._isIdentity = value; } }
        public Type SysType { get { return this._sysType; } set { this._sysType = value; } }
        public string CoumnName { get { return this._columnName; } set { this._columnName = value; } }
        public DbType DataType { get { return this._dataType; } set { this._dataType = value; } }
        public BaseColumn(string columnName,object value,Type sysType, DbType dataType,bool isPK,bool isIdentity)
        {
            this._columnName = columnName;
            this._dataType = dataType;
            this._sysType = sysType;
            this._isPk = isPK;
            this._isIdentity = isIdentity;
            this._value = value;
        }
        public BaseColumn(string columnName)
            : this(columnName, null,null, DbType.String,false,false)
        {
        }
        public BaseColumn(string columnName, object value)
            : this(columnName, value, null, DbType.String, false, false)
        {
        }
        public BaseColumn(string columnName, object value, Type sysType)
            : this(columnName, value, sysType, DbType.String, false, false)
        {
        }
        public BaseColumn(string columnName, object value, Type sysType, DbType dataType)
            : this(columnName,value, sysType, dataType, false, false)
        {
        }
        public BaseColumn(string columnName, object value, Type sysType, DbType dataType, bool isPK)
            : this(columnName,value, sysType, dataType, isPK, false)
        {

        }
    }

 

    /// <summary>
    /// 提供数据访问操作的基本实现
    /// </summary>
    class BaseTable
    {
        private object _inheritObject;
        private bool _isPrepared;
        private List<BaseColumn> _columns;
        private string _inheritObjectName;
        private StringBuilder _sqlSentence = new StringBuilder();
        protected object InheritObject
        {
            get { return _inheritObject; }
            set { _inheritObject = value; }
        }
        public virtual void ExecuteAppend()
        {
            PrepareInherit();
            _sqlSentence.Append("insert into ");
            _sqlSentence.Append(_inheritObjectName);
            _sqlSentence.Append(" (");
            foreach (BaseColumn col in _columns)
            {
                _sqlSentence.Append(col.CoumnName);
                if (!_columns.LastIndexOf(col).Equals(_columns.Count - 1))
                    _sqlSentence.Append(",");
            }
            _sqlSentence.Append(" )");
            _sqlSentence.Append(" values(");
            ///此处省略若干Parameter形式进行数据库操作
            foreach (BaseColumn col in _columns)
            {
                _sqlSentence.Append("'");
                _sqlSentence.Append(col.Value.ToString());
                _sqlSentence.Append("'");
                if (!_columns.LastIndexOf(col).Equals(_columns.Count - 1))
                    _sqlSentence.Append(",");
            }
            _sqlSentence.Append(" )");
            Console.WriteLine("Sql sentence is:");
            Console.WriteLine(_sqlSentence.ToString());
            Console.Read();
        }
        public virtual void ExecuteDelete()
        {
            PrepareInherit();
            Console.WriteLine("Please call ExecuteAppend because current method no implemented.");
            Console.Read();
        }
        public virtual void ExecuteUpdate()
        {
            PrepareInherit();
            Console.WriteLine("Please call ExecuteAppend because current method no implemented.");
            Console.Read();
        }
        private void PrepareInherit()
        {
            if (!_isPrepared)
            {
                _inheritObjectName = PrepareObject();
                _columns = PrepareColumn();
                _isPrepared = true;
            }          
        }
        private string PrepareObject()
        {
            return (this._inheritObject.GetType().GetCustomAttributes(typeof(CustomTableAttribute), false) as CustomTableAttribute[])[0].TableName;
        }
        private List<BaseColumn> PrepareColumn()
        {
            List<BaseColumn> columns = new List<BaseColumn>();
            BaseColumn curCol = null;
            foreach (PropertyInfo column in this._inheritObject.GetType().GetProperties())
            {
                CustomColumnAttribute[] columnAttributes = (CustomColumnAttribute[])column.GetCustomAttributes(typeof(CustomColumnAttribute), false);
                curCol = new BaseColumn(columnAttributes[0].ColumnName);
                curCol.SysType = column.PropertyType;
                ///此处省略进行一个自定义的类型转换
                curCol.DataType = System.Data.DbType.Boolean;
                curCol.IsIdentity = columnAttributes[0].IsIdentity;
                curCol.IsPK = columnAttributes[0].IsPK;
                curCol.Value = column.GetValue(this._inheritObject, null);
                columns.Add(curCol);
            }
            return columns;
        }
    }

 

    /// <summary>
    /// 示例数据表对象:代码可由代码生成器生成
    /// </summary>
    [CustomTable("DemoTable")]
    class DataTable:BaseTable
    {
        public DataTable()
        {
            base.InheritObject = this;
        }
        private string _column1;
        private string _column2;
        private DateTime _column3;
        [CustomColumn("col_1",true,false)]
        public string Column1
        {
            get { return this._column1; }
            set { this._column1 = value; }
        }
        [CustomColumn("col_2")]
        public string Column2
        {
            get { return this._column2; }
            set { this._column2 = value; }
        }
        [CustomColumn("col_3")]
        public DateTime Column3
        {
            get { return this._column3; }
            set { this._column3 = value; }
        }       
    }

 

   class Program
    {
        /// <summary>
        /// 运行进程
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            DataTable demoTable = new DataTable();
            demoTable.Column1 = "some value just in column1 in dataBase";
            demoTable.Column2 = "some value just in column2 in dataBase";
            demoTable.Column3 = System.DateTime.Now;
            demoTable.ExecuteAppend();
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值