/summary&gt要把数据库里之表和实体类对应.这样。

非赘述了。直接代码!

众人犹清楚工厂,知道反射,但是确能够就此的好的连无多,我吗是近期才真的理解了哟是反射,反射和.Net 里之有别样特色是怎下的。在此地,分享一个和谐写的多少之数据库工厂的架,和大家谈谈。

365体育网投 1365体育网投 2Code
public class Cls_EnumHandle
    {
        public string GetDescription(Enum value)
        {
            if (value == null) throw new ArgumentNullException(“value”);
            string description = value.ToString();
            FieldInfo fieldInfo = value.GetType().GetField(description);
            EnumDescriptionAttribute[] attr = (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
            if (attr != null && attr.Length > 0)
            {
                description = attr[0].Description;
            } 

目的的急需

            return description;
        } 

当一个系里,需要出一个联结的数目库类实现对SQL Server的增删改查
,要求发生可以的恢宏行与维护性。

        public IList ToList(Type type)
        {
            if (type == null) throw new ArgumentNullException(“type”);
            if (!type.IsEnum) throw new ArgumentException(“Type provided must be an Enum.”, “type”); 

当领略反射和特性之前的思绪,是对准每个实体类写相应的操作。但是现在,可以通过动用Attribute来进展自己定义

            ArrayList list = new ArrayList();
            Array array = Enum.GetValues(type);
            foreach (Enum value in array)
            { 
                list.Add(new KeyValuePair<Enum,string>(value,GetDescription(value)));
            } 

先是,要把数据库里的表和实体类对应.这样,我们大概的概念一个性ClassesDefineSqlAttribute,用对应表和实体类。

            return list;
        }
    } 

 

    [AttributeUsage(AttributeTargets.Enum|AttributeTargets.Field,AllowMultiple=false)]
    public class EnumDescriptionAttribute : Attribute
    {
        private string description; 

[AttributeUsage(AttributeTargets.Class)]
    class ClassesDefineSqlAttribute :Attribute 
    {
        public String SqlTableName { get; set; }
        public ClassesDefineSqlAttribute()
        {
          
        }

        public string Description
        {
            get
            {
                return this.description;
            }
        } 

    }

        public EnumDescriptionAttribute(string description) : base()
        {
            this.description = description;
        }
    } 

 

/// <summary>
    /// 字体意义
    /// </summary>
    enum FontMean
    { 
        /// <summary>
        /// 正文
        /// </summary>
        [EnumDescription(“正文”)]
        Main,
        /// <summary>
        /// 批注
        /// </summary>
        [EnumDescription(“批注”)]
        Postil,
        /// <summary>
        /// 双列小字
        /// </summary>
        [EnumDescription(“双列小字”)]
        Double,
        /// <summary>
        /// 三列小字
        /// </summary>
        [EnumDescription(“三排列小字”)]
        Three,
        /// <summary>
        /// 四排小字
        /// </summary>
        [EnumDescription(“四列小字”)]
        Four,
        /// <summary>
        /// 五排列小字
        /// </summary>
        [EnumDescription(“五列小字”)]
        Five,
        /// <summary>
        /// 插入字
        /// </summary>
        [EnumDescription(“插入字”)]
        Insert,
        /// <summary>
        /// 其它
        /// </summary>
        [EnumDescription(“其它”)]
        Other
    } 

率先步对应好了后来,下一致步要将实体类的属性与数据库表中的排列进行相应,为者,定义
ClassesDefineColumnAttribute 这里,只是略的安装了列名,列的门类(数据,主键,改前的主键),呵呵,一切从简,够用就好

cbxFontType.DataSource = new Cls_EnumHandle().ToList(typeof(FontMean));
cbxFontType.DisplayMember = “Value”;
cbxFontType.ValueMember = “Key”;

 

    public enum ColType
    {
        /// <summary>
        /// 数据列
        /// </summary>
        Data,
        /// <summary>
        /// 主键列
        /// </summary>
        ClassCode,
        /// <summary>
        /// 级别列(在树型结构中之所以到)
        /// </summary>
        ClassLevel,
        /// <summary>
        /// 旧键(更新时行使)
        /// </summary>
        OldCode
    }
    [AttributeUsage(AttributeTargets.Property )]
    public class ClassesDefineColumnAttribute:Attribute 
    {
        //对应之数据库列名
        public string SqlColName { get; set; }
        /// <summary>
        /// 列的型
        /// </summary>
        public ColType ColType { get; set; }

        /// <summary>
        /// 复杂类型的属性值 
        /// </summary>
        public string TargetProperty { get; set; }
      
    }
}

 

 

故而了这些准备,就得于数据工厂被成就增删改查了

为通用,我们把增删改之参数都安成object 
,这样,在操作时,先将object
的末段路取到,然后取地方的几乎只属性,动态的生成SQL语句

先期看多操作

 

        public void Create(object T)
        {
            var info = T.GetType();//得到要新建的档次
            ClassesDefineSqlAttribute attribute =
                (ClassesDefineSqlAttribute)Attribute.GetCustomAttribute(info,
                typeof(ClassesDefineSqlAttribute));///得到表名

            if (attribute != null)
            {

                var Properties = info.GetProperties();///得到性
                System.Reflection.PropertyInfo KeyProperty = null;
                String insert = “INSERT ” + attribute.SqlTableName + “(“;
                String values = “) Values(“;
                String checksql = “”;

                String GetKeySql = “WHERE 1=1”;

 
                foreach (var infoattr in Properties)
                {
                     
                    var ob = Attribute.GetCustomAttribute(infoattr, typeof(ClassesDefineColumnAttribute));

                    if (ob != null)
                    {
                        var attr = ob as ClassesDefineColumnAttribute;

                        if (attr is ClassesDefineColumnAttribute)
                        {

                            var a = attr as ClassesDefineColumnAttribute;
                            if (a.ColType != ColType.OldCode)
                            {

                                if (a.ColType != ColType.ClassCode
                                   ||
                                    infoattr.PropertyType == typeof(String))
                                {

                                    string valuestr = (infoattr.GetValue(T, null) ?? “”).ToString();
                                    insert += a.SqlColName + “,”;
                                    values += “‘” + valuestr + “‘,”;
                                    GetKeySql = GetKeySql + ” And ” + a.SqlColName + “='” + valuestr + “‘”;
                                }
                                if (a.ColType == ColType.ClassCode)
                                {

                                    KeyProperty = infoattr;
                                    if (KeyProperty.PropertyType == typeof(String))
                                    {

                                        checksql = “Select Count(*) FROM ” + attribute.SqlTableName + ” Where ” + a.SqlColName + “='” + (infoattr.GetValue(T, null) ?? “”).ToString() + “‘”;
                                        if (System.Convert.ToInt32(
                                            new DataConnectionFactory().GetDataTable(checksql).Rows[0][0]) > 0)
                                            throw new Exception(“无法充分成新数据,与现有数据编码相同!”);
                                    }
                                    else
                                    {
                                        GetKeySql = “Select ” + a.SqlColName + ” FROM ” + attribute.SqlTableName + ” ” + GetKeySql;
                                    }
                                }

                            }
                        }

                    }
                }
               
                String sql = insert.Substring(0, insert.Length – 1) + values.Substring(0, values.Length – 1) + “)”;

                using (var db = new DataConnectionFactory().GetConnection())
                {
                    db.ExecuteCommand(sql);

                    //设置 自增长主键的归直

                    if (KeyProperty.PropertyType != typeof(string))
                    {
                        KeyProperty.SetValue(T,
                            new DataConnectionFactory().GetDataTable(GetKeySql).Rows[0][0], null);
                    }

                }

            }
            else
            {
                throw new Exception(“类型不符合要求”);
            }

        }

增加操作完成,改的操作也很接近

 

        public void Save(object T)
        {
            var info = T.GetType();
            ClassesDefineSqlAttribute attribute = (ClassesDefineSqlAttribute)Attribute.GetCustomAttribute(info, typeof(ClassesDefineSqlAttribute));
            String oldCode = “”;
            String newCode = “”;

            bool HaveOldCode = false;

 
            System.Reflection.PropertyInfo KeyProperty = null;

            if (attribute != null)
            {

                var Properties = info.GetProperties();
                String insert = “UPDATE ” + attribute.SqlTableName + ” SET “;
                String wheresql = “”;

                String checksql = “”;

                foreach (var infoattr in Properties)
                {
                   
                    var ob = Attribute.GetCustomAttribute(infoattr, typeof(ClassesDefineColumnAttribute));

                    if (ob != null)
                    {
                        var attr = ob as ClassesDefineColumnAttribute;
                        if (attr is ClassesDefineColumnAttribute)
                        {
                            var valueStr = infoattr.GetValue(T, null).ToString();

                            var a = attr as ClassesDefineColumnAttribute;
                            if (attr.ColType == ColType.Data
                                || (attr.ColType == ColType.ClassCode && infoattr.PropertyType == typeof(String)))
                                insert += a.SqlColName + “='” + valueStr + “‘,”;

                            if (a.ColType == ColType.ClassCode)
                            {
                                checksql = a.SqlColName + “='” + valueStr + “‘”;
                                KeyProperty = infoattr;
                                newCode = valueStr;
                            }
                            if (a.ColType == ColType.OldCode)
                            {
                                HaveOldCode = true;
                                wheresql = ” Where ” + a.SqlColName + “='” + valueStr + “‘”;
                                oldCode = valueStr;

                            }
                        }

                    }
                }

               

                if (HaveOldCode)
                {
                    if (newCode != oldCode)
                    {

                        checksql = “Select count(*) FROM ” + attribute.SqlTableName + wheresql + ” OR  ” + checksql;

                        if (System.Convert.ToInt32(
                            new DataConnectionFactory().GetDataTable(checksql).Rows[0][0]) >= 2)
                            throw new Exception(“无法充分成新数据,与存活数据编码相同!”);
                    }
                }
                else
                    wheresql = “Where ” + checksql;
                String sql = insert.Substring(0, insert.Length – 1) + wheresql;
                using (var db = new DataConnectionFactory().GetConnection())
                {
                    db.ExecuteCommand(sql);
                }

            }
            else
            {
                throw new Exception(“类型不符合要求”);
            }

        }

末尾是去的操作

 

     public void Delete(object T)
        {
            var info = T.GetType();
            ClassesDefineSqlAttribute attribute = (ClassesDefineSqlAttribute)Attribute.GetCustomAttribute(info, typeof(ClassesDefineSqlAttribute));
            TreeNodeAttribute treedef = (TreeNodeAttribute)Attribute.GetCustomAttribute(info, typeof(TreeNodeAttribute));
       

            if (attribute != null)
            {

                var Properties = info.GetProperties();
                String insert = “Delete ” + attribute.SqlTableName + ” “;
                

                foreach (var infoattr in Properties)
                {                     var ob = Attribute.GetCustomAttribute(infoattr, typeof(ClassesDefineColumnAttribute));

                    if (ob != null)
                    {
                        var attr = ob as ClassesDefineColumnAttribute;
                        if (attr is ClassesDefineColumnAttribute)
                        {
                            var valueStr = infoattr.GetValue(T, null).ToString();

                            var a = attr as ClassesDefineColumnAttribute;
                           
                            if (a.ColType == ColType.OldCode)
                            {

                                insert  += ” Where ” + a.SqlColName + “='” + valueStr + “‘”;

                                break;

                            }
                            else if (a.ColType == ColType.ClassCode)
                            {
                                insert += ” Where ” + a.SqlColName + “='” + valueStr + “‘”;

                                break;
                            }
                        }

                    }
                }
                String sql = insert;

          
                using (var db = new DataConnectionFactory().GetConnection())
                {
                    db.ExecuteCommand(sql);
                }

            }
            else
            {
                throw new Exception(“类型不符合要求”);
            }

        }

 

这么,再起型 ,只要做好对应的记,便 可直接运用之看似了

设本人的意味档案盒的型FileBox

 

    [ClassesDefineSql(SqlTableName = “DA_FileBox”)]
    public class FileBox
    {
        /// <summary>
        /// 档案盒
        /// </summary>
        [ClassesDefineColumn(ColType = ColType.ClassCode, SqlColName = “BoxNo”)]
        public String BoxNo
        {
            get;
            set;
        }

        /// <summary>
        /// 标签ID
        /// </summary>
        [ClassesDefineColumn(ColType = ColType.Data, SqlColName = “TagNo”)]
        public string TagID
        {
            get;
            set;
        }

        /// <summary>
        /// 类别信息
        /// </summary>
        [ClassesDefineColumn(ColType = ColType.Data, SqlColName = “ClassNo”)]
        public string ClassNo
        {
            get;
            set;
        }

        /// <summary>
        /// 类别称号
        /// </summary>
        [ClassesDefineColumn(ColType = ColType.Data, SqlColName = “ClassName”)]
        public string ClassName
        {
            get;
            set;
        }

        /// <summary>
        /// 位置编号
        /// </summary>

        [ClassesDefineColumn(ColType = ColType.Data, SqlColName = “LocationNo”)]
        public string LocationNo
        {
            get;
            set;
        }

        /// <summary>
        /// 位置说明
        /// </summary>

        [ClassesDefineColumn(ColType = ColType.Data, SqlColName = “LocationName”)]
        public string LocationName
        {
            get;
            set;
        }

        /// <summary>
        /// 备用一
        /// </summary>
        [ClassesDefineColumn(ColType = ColType.Data, SqlColName = “Note1”)]
        public string Note1
        {
            get;
            set;
        }

        /// <summary>
        /// 备用二
        /// </summary>
        [ClassesDefineColumn(ColType = ColType.Data, SqlColName = “Note2”)]
        public string Note2
        {
            get;
            set;
        }
    }

 

 

相关文章