示例#1
0
        //创建文件数据库,并添加50条数据。
        void CreateTable()
        {
            Response.Write("文章见:http://www.cnblogs.com/cyq1162/p/3443244.html <hr />");
            if (DBTool.ExistsTable(tableName))
            {
                using (MAction action = new MAction(tableName))
                {
                    if (action.Fill("order by id desc"))
                    {
                        action.Delete("id<=" + action.Get <int>(0));
                    }
                }
                //DBTool.DropTable(tableName);
            }
            else
            {
                MDataColumn mdc = new MDataColumn();
                mdc.Add("ID", SqlDbType.Int, true);
                mdc.Add("Name");
                mdc.Add("CreateTime", SqlDbType.DateTime);
                DBTool.CreateTable(tableName, mdc);
            }
            MDataTable dt = new MDataTable(tableName);

            dt.Columns = DBTool.GetColumns(tableName);
            for (int i = 0; i < 60; i++)
            {
                dt.NewRow(true).Set(1, "Name_" + i).Set(2, DateTime.Now.AddSeconds(i));
            }
            dt.AcceptChanges(AcceptOp.Insert);
        }
示例#2
0
        private void Init(MDataTable mTable, string conn)
        {
            if (mTable.Columns == null || mTable.Columns.Count == 0)
            {
                Error.Throw("MDataTable's columns can't be null or columns'length can't be zero");
            }
            if (string.IsNullOrEmpty(mTable.TableName))
            {
                Error.Throw("MDataTable's tablename can't  null or empty");
            }
            mdt = sourceTable = mTable;

            if (mdt.TableName.IndexOfAny(new char[] { '(', ')' }) > -1)
            {
                mdt.TableName = mdt.TableName.Substring(mdt.TableName.LastIndexOf(')') + 1).Trim();
            }

            _Conn = !string.IsNullOrEmpty(conn) ? conn : mTable.Conn;
            if (!DBTool.ExistsTable(mdt.TableName, _Conn, out dalTypeTo, out database))
            {
                if (!DBTool.CreateTable(mdt.TableName, mdt.Columns, _Conn))
                {
                    Error.Throw("Create Table Error:" + mdt.TableName);
                }
            }
            MDataColumn column = DBTool.GetColumns(mdt.TableName, _Conn);

            FixTable(column);//
            if (mdt.Columns.Count == 0)
            {
                Error.Throw("After fix table columns, length can't be zero");
            }
            SetDbBaseForTransaction();
        }
示例#3
0
        /// <summary>
        /// 获得数据库名称
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public static string GetDBName(string tableName)
        {
            foreach (KeyValuePair <string, Dictionary <string, string> > item in DbTables)
            {
                if (item.Value.ContainsKey(tableName))
                {
                    return(item.Key);
                }
            }
            //找不到时,可能是视图,根据数据库类型匹配第一个可能的数据库
            foreach (KeyValuePair <string, DalType> item in _DbTypeDic)
            {
                switch (item.Value)
                {
                case DalType.Txt:
                case DalType.Xml:
                    break;

                default:
                    MDataColumn mdc = DBTool.GetColumns(item.Key + "." + tableName);
                    if (mdc != null && mdc.Count > 0)
                    {
                        if (!DbTables[item.Key].ContainsKey(tableName))
                        {
                            DbTables[item.Key].Add(tableName, "");    //添加视图或未缓存的表
                        }
                        return(item.Key);
                    }
                    break;
                }
            }
            return("");
        }
示例#4
0
 static void LoadViewSchema(object para)
 {
     try
     {
         Dictionary <string, string> fileList = SqlCode.FileList;
         if (fileList != null && fileList.Count > 0)
         {
             foreach (KeyValuePair <string, string> item in fileList)
             {
                 if (item.Key.StartsWith("V_"))//视图文件
                 {
                     string sql = "";
                     if (item.Value.Contains(":\\"))//存档的是文件路径
                     {
                         sql = SqlCode.GetCode(item.Key);
                     }
                     else
                     {
                         sql = item.Value;
                     }
                     if (sql.IndexOf('@') == -1)//仅处理无参数的。
                     {
                         DBTool.GetColumns(sql, GetConn(sql));
                     }
                 }
             }
         }
     }
     catch
     {
     }
 }
示例#5
0
        private static void FillTable(string objName, string objCode, MDataTable dt)
        {
            Dictionary <string, string> fieldTitleDic = GridConfig.FieldTitle;
            MDataColumn mdc  = DBTool.GetColumns(CrossDb.GetEnum(objCode));
            MCellStruct cell = null;
            int         jointPrimaryCount = mdc.JointPrimary.Count;

            for (int i = 0; i < mdc.Count; i++)
            {
                cell = mdc[i];
                MDataRow row = dt.NewRow();
                row.Set(Config_Grid.ObjName, objName);
                row.Set(Config_Grid.Field, cell.ColumnName);
                row.Set(Config_Grid.Title, fieldTitleDic.ContainsKey(cell.ColumnName) ? fieldTitleDic[cell.ColumnName] : cell.ColumnName);
                row.Set(Config_Grid.Hidden, i == 0 && jointPrimaryCount < 2);
                row.Set(Config_Grid.OrderNum, (i + 1) * 10);
                row.Set(Config_Grid.Width, 100);
                row.Set(Config_Grid.Sortable, i > 0);
                row.Set(Config_Grid.Import, i > 0);
                row.Set(Config_Grid.Export, i > 0);
                row.Set(Config_Grid.Colspan, 1);
                row.Set(Config_Grid.Rowspan, 1);
                row.Set(Config_Grid.Edit, i > 0 || jointPrimaryCount > 1);
                row.Set(Config_Grid.Frozen, i < 4);
                row.Set(Config_Grid.Align, "center");
                string value = DataType.GetType(cell.SqlType).Name.ToLower() + "," + cell.MaxSize + "," + cell.Scale + (cell.IsCanNull ? ",0" : ",1") + (cell.IsPrimaryKey ? ",1" : ",0");
                row.Set(Config_Grid.DataType, value);
                if (i == 0)
                {
                    if (jointPrimaryCount < 2)
                    {
                        row.Set(Config_Grid.Formatter, "#");
                    }
                }
                else
                {
                    switch (DataType.GetGroup(cell.SqlType))
                    {
                    case 2:
                        row.Set(Config_Grid.Formatter, "dateFormatter");
                        break;

                    case 3:
                        row.Set(Config_Grid.Formatter, "boolFormatter");
                        break;

                    default:
                        if (cell.MaxSize > 50)
                        {
                            row.Set(Config_Grid.Formatter, "stringFormatter");
                        }
                        break;
                    }
                }
                dt.Rows.Add(row);
            }
        }
示例#6
0
        private static void FillTable(string objName, MDataTable dt)
        {
            string formatObjName = objName.Contains(" ") ? objName.Substring(objName.LastIndexOf(' ')).Trim() : objName;
            Dictionary <string, string> fieldTitleDic = GridConfig.FieldTitle;
            MDataColumn mdc  = DBTool.GetColumns(CrossDb.GetEnum(objName));
            MCellStruct cell = null;

            for (int i = 0; i < mdc.Count; i++)
            {
                cell = mdc[i];
                MDataRow row = dt.NewRow();
                row["ObjName"].Value   = formatObjName;
                row["Field"].Value     = cell.ColumnName;
                row["Title"].Value     = fieldTitleDic.ContainsKey(cell.ColumnName) ? fieldTitleDic[cell.ColumnName] : cell.ColumnName;
                row["Hidden"].Value    = i == 0;//隐藏主键
                row["Formatter"].Value = i == 0 ? "#" : "";
                row["OrderNum"].Value  = (i + 1) * 10;
                row["Width"].Value     = 100;//第一个主键列<10,则由图标个数*36 自动控制。
                row["Sortable"].Value  = i > 0;
                row["Import"].Value    = i > 0 && !cell.IsCanNull;
                row["Export"].Value    = true;
                row["Edit"].Value      = i > 0;
                row["Frozen"].Value    = i < 4;
                row["Align"].Value     = "center";
                row["DataType"].Value  = DataType.GetType(cell.SqlType).Name.ToLower() + "," + cell.MaxSize + "," + cell.Scale + "," + (cell.IsCanNull ? 0 : 1);
                if (i > 0)
                {
                    switch (DataType.GetGroup(cell.SqlType))
                    {
                    //case 1:
                    //    row["DataType"].Value = "int";
                    //    break;
                    case 2:
                        //row["DataType"].Value = "datetime";
                        row["Formatter"].Value = "dateFormatter";
                        break;

                    case 3:
                        //row["DataType"].Value = "bool";
                        row["Formatter"].Value = "boolFormatter";
                        break;

                    default:
                        //row["DataType"].Value = "string";
                        if (cell.MaxSize > 50)
                        {
                            row["Formatter"].Value = "stringFormatter";
                        }
                        break;
                    }
                }
                dt.Rows.Add(row);
            }
        }
示例#7
0
        private void Init(MDataTable mTable, string conn)
        {
            if (mTable.Columns == null || mTable.Columns.Count == 0)
            {
                Error.Throw("MDataTable's columns can't be null or columns'length can't be zero");
            }
            if (string.IsNullOrEmpty(mTable.TableName))
            {
                Error.Throw("MDataTable's tablename can't  null or empty");
            }
            mdt = sourceTable = mTable;

            if (mdt.TableName.IndexOfAny(new char[] { '(', ')' }) > -1)
            {
                mdt.TableName = mdt.TableName.Substring(mdt.TableName.LastIndexOf(')') + 1).Trim();
            }
            if (!string.IsNullOrEmpty(conn))
            {
                _Conn = conn;
            }
            else
            {
                if (mTable.DynamicData != null && mTable.DynamicData is MAction)//尝试多动态中获取链接
                {
                    _Conn = ((MAction)mTable.DynamicData).ConnString;
                }
                else if (mTable.DynamicData != null && mTable.DynamicData is MProc)
                {
                    _Conn = ((MProc)mTable.DynamicData).ConnString;
                }
                else
                {
                    _Conn = mTable.Conn;
                }
            }

            if (!DBTool.Exists(mdt.TableName, "U", _Conn))
            {
                DBTool.ErrorMsg = null;
                if (!DBTool.CreateTable(mdt.TableName, mdt.Columns, _Conn))
                {
                    Error.Throw("Create Table Error:" + mdt.TableName + DBTool.ErrorMsg);
                }
            }
            MDataColumn column = DBTool.GetColumns(mdt.TableName, _Conn);

            FixTable(column);//
            if (mdt.Columns.Count == 0)
            {
                Error.Throw("After fix table columns, length can't be zero");
            }
            dalTypeTo = column.DataBaseType;
            SetDalBaseForTransaction();
        }
示例#8
0
        /// <summary>
        /// 读取数据库所有表
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="filter">过滤条件值</param>
        /// <returns></returns>
        public static MDataTable Get(string key, string filter)
        {
            MDataTable dt = null;
            SortedDictionary <string, string> newDic = new SortedDictionary <string, string>();

            switch (key)
            {
            case "C_SYS_Table":
                if (!string.IsNullOrEmpty(filter))
                {
                    if (CrossDb.DbTables.ContainsKey(filter))
                    {
                        foreach (var item in CrossDb.DbTables[filter])
                        {
                            newDic.Add(item.Key, item.Key);
                        }
                    }
                }
                else
                {
                    foreach (var tableDic in CrossDb.DbTables)
                    {
                        foreach (var item in tableDic.Value)
                        {
                            newDic.Add(item.Key, item.Key);
                        }
                    }
                }
                break;

            case "C_SYS_Column":
                if (!string.IsNullOrEmpty(filter))
                {
                    MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(filter));
                    foreach (var item in mdc)
                    {
                        newDic.Add(item.ColumnName, item.ColumnName);
                    }
                }
                break;
            }
            dt = MDataTable.CreateFrom(newDic);
            if (dt != null)
            {
                dt.Columns[0].ColumnName = "value";
                dt.Columns[1].ColumnName = "text";
                if (dt.Columns.Count > 2)
                {
                    dt.Columns[2].ColumnName = "parent";
                }
            }
            return(dt);
        }
示例#9
0
        private static void FillTable(string objName, MDataTable dt)
        {
            string formatObjName = objName.Contains(" ") ? objName.Substring(objName.LastIndexOf(' ')).Trim() : objName;
            Dictionary <string, string> fieldTitleDic = GridConfig.FieldTitle;
            MDataColumn mdc  = DBTool.GetColumns(CrossDb.GetEnum(objName));
            MCellStruct cell = null;

            for (int i = 0; i < mdc.Count; i++)
            {
                cell = mdc[i];
                MDataRow row = dt.NewRow();
                row.Set(Config_Grid.ObjName, formatObjName);
                row.Set(Config_Grid.Field, cell.ColumnName);
                row.Set(Config_Grid.Title, fieldTitleDic.ContainsKey(cell.ColumnName) ? fieldTitleDic[cell.ColumnName] : cell.ColumnName);
                row.Set(Config_Grid.Hidden, i == 0);
                row.Set(Config_Grid.OrderNum, (i + 1) * 10);
                row.Set(Config_Grid.Width, 100);
                row.Set(Config_Grid.Sortable, i > 0);
                row.Set(Config_Grid.Import, i > 0);
                row.Set(Config_Grid.Export, i > 0);
                row.Set(Config_Grid.Colspan, 1);
                row.Set(Config_Grid.Rowspan, 1);
                row.Set(Config_Grid.Edit, i > 0);
                row.Set(Config_Grid.Frozen, i < 4);
                row.Set(Config_Grid.Align, "center");
                row.Set(Config_Grid.DataType, DataType.GetType(cell.SqlType).Name.ToLower() + "," + cell.MaxSize + "," + cell.Scale + "," + (cell.IsCanNull ? 0 : 1));
                if (i == 0)
                {
                    row.Set(Config_Grid.Formatter, "#");
                }
                else
                {
                    switch (DataType.GetGroup(cell.SqlType))
                    {
                    case 2:
                        row.Set(Config_Grid.Formatter, "dateFormatter");
                        break;

                    case 3:
                        row.Set(Config_Grid.Formatter, "boolFormatter");
                        break;

                    default:
                        if (cell.MaxSize > 50)
                        {
                            row.Set(Config_Grid.Formatter, "stringFormatter");
                        }
                        break;
                    }
                }
                dt.Rows.Add(row);
            }
        }
示例#10
0
        /// <summary>
        /// 得到enum
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="tableName_displayName">表名(显示名[数据库中备注的名称])</param>
        /// <param name="config"></param>
        /// <returns></returns>
        private static string GetFiledEnum(string tableName, string tableName_displayName, ProjectConfig config)
        {
            StringBuilder builder = new StringBuilder();

            // 处理回车或换行
            tableName_displayName = tableName_displayName.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");;
            tableName_displayName = tableName_displayName == "" ? tableName : tableName_displayName;


            builder.AppendFormat("    #region [    表名:{0}    备注名:{1}    ]\r\n", tableName.PadRight(45), tableName_displayName.PadRight(30));
            builder.AppendFormat("    /// <summary>\r\n", string.Empty);
            builder.AppendFormat("    /// enum 表名:{0}\r\n", tableName_displayName);
            builder.AppendFormat("    /// </summary>\r\n", string.Empty);
            builder.AppendFormat("    public enum {0}\r\n", FormatKey(tableName));
            builder.AppendFormat("    {{");
            try
            {
                MDataColumn columns = DBTool.GetColumns(tableName, config.Conn);
                if (columns.Count > 0)
                {
                    for (int i = 0; i < columns.Count; i++)//进行列的输出
                    {
                        string str = FormatKey(columns[i].ColumnName);
                        // 处理回车或换行
                        string strDisplayName = columns[i].Description.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");;
                        strDisplayName = strDisplayName == "" ? str : strDisplayName;

                        builder.AppendFormat("\r\n");
                        builder.AppendFormat("        /// <summary>\r\n", string.Empty);
                        builder.AppendFormat("        /// enum 字段名:{0}\r\n", strDisplayName);
                        builder.AppendFormat("        /// </summary>\r\n", string.Empty);
                        builder.AppendFormat("        [Display(Name = \"{0}\")]\r\n", strDisplayName);

                        builder.AppendFormat("        {0} ,\r\n", str, strDisplayName);
                    }
                    builder.Append("    }\r\n");
                }
                else
                {
                    builder.Append("    }\r\n");
                }
            }
            catch (Exception exception)
            {
                CYQ.Data.Log.WriteLogToTxt(exception);
            }
            builder.AppendFormat("    #endregion\r\n");


            return(builder.ToString());
        }
示例#11
0
        /// <summary>
        /// 生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_create_Click(object sender, EventArgs e)
        {
            var nameSpace = textBox_nameSpace.Text;
            var tableName = comboBox_tables.Text;
            //var cols = DBTool.GetColumns(tableName, _conn);
            var text = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace " + nameSpace + "{\n";

            text += @"public class " + tableName + "{";
            var cols = DBTool.GetColumns(tableName, _conn);

            foreach (var col in cols)
            {
                var note = col.Description;
                var name = col.ColumnName;
                var cc   = GetType(col.SqlType, DalType.MsSql);
                text += String.Format(@"
        /// <summary>
        /// {0}
        /// </summary>
        /// <returns></returns>
        public {1} {2} {{get;set;}}", note, cc, name);
            }
            text += "\n}\n}";
            textBox_result.Text = text;

            if (checkBox_savefile.Checked)
            {
                var path = Directory.GetCurrentDirectory() + "/Model/" + tableName + ".cs";
                var flag = IOHelper.Write(path, text);
                var msg  = flag ? "生成成功" : "生成失败";
                MessageBox.Show(msg);
            }
        }
示例#12
0
        public static Dictionary <string, string> GetTitleField(string tableName)
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();
            MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(tableName));

            if (mdc.Count > 0)
            {
                foreach (MCellStruct item in mdc)
                {
                    string des = Convert.ToString(item.Description);
                    if (!string.IsNullOrEmpty(des))
                    {
                        des = des.Split(new char[] { ' ', ',', '(' })[0];
                        if (!dic.ContainsKey(des))
                        {
                            dic.Add(des, item.ColumnName);
                        }
                    }
                }
            }
            return(dic);
        }
示例#13
0
        public string GetExcelMapping()
        {
            MDataRow row     = ExcelConfig.GetExcelRow(Query <string>("ID"));
            string   objName = row.Get <string>(Config_Excel.ExcelName);

            string[] TableNames             = row.Get <string>(Config_Excel.TableNames).Split(',');
            Dictionary <string, string> dic = new Dictionary <string, string>();
            JsonHelper js = new JsonHelper();

            foreach (string name in TableNames)
            {
                MDataColumn mdc = DBTool.GetColumns(name);
                js.Add(name, GetJson(mdc), true);
                dic.Add(name, name);
            }
            JsonHelper jh = new JsonHelper();

            jh.Add("objName", objName);
            jh.Add("arrColumns", js.ToString(false));
            jh.Add("arrTables", MDataTable.CreateFrom(dic).ToJson(false, false));
            return(jh.ToString());
        }
示例#14
0
        static string GetFiledEnum(string tableName, ProjectConfig config)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("    public enum " + FormatKey(tableName) + " {");
            try
            {
                MDataColumn column = DBTool.GetColumns(tableName, config.Conn);

                if (column.Count > 0)
                {
                    for (int i = 0; i < column.Count; i++)
                    {
                        string cName = FormatKey(column[i].ColumnName);
                        if (i == 0)
                        {
                            sb.Append(" " + cName);
                        }
                        else
                        {
                            sb.Append(", " + cName);
                        }
                    }
                    sb.Append(" }\r\n");
                }
                else
                {
                    sb.Append("}\r\n");
                    // tableColumnNames = tableColumnNames + "}\r\n";
                }
            }
            catch (Exception err)
            {
                Log.WriteLogToTxt(err);
            }
            return(sb.ToString());
        }
示例#15
0
        /// <summary>
        /// 将原有的初始化改造成延时加载。
        /// </summary>
        private void SetDelayInit(Object entityInstance, string tableName, string conn, AopOp op)
        {
            if (string.IsNullOrEmpty(conn))
            {
                //不设置链接,则忽略(当成普通的实体类)
                return;
            }
            entity   = entityInstance;
            typeInfo = entity.GetType();
            try
            {
                if (string.IsNullOrEmpty(tableName))
                {
                    tableName = typeInfo.Name;
                    if (tableName.EndsWith(AppConfig.EntitySuffix))
                    {
                        tableName = tableName.Substring(0, tableName.Length - AppConfig.EntitySuffix.Length);
                    }
                }

                string key = tableName + StaticTool.GetHashKey(conn);
                if (!CacheManage.LocalInstance.Contains(key))
                {
                    DalType dal      = DBTool.GetDalType(conn);
                    bool    isTxtDal = dal == DalType.Txt || dal == DalType.Xml;
                    string  errMsg   = string.Empty;
                    Columns = DBTool.GetColumns(tableName, conn, out errMsg);//内部链接错误时抛异常。
                    if (Columns == null || Columns.Count == 0)
                    {
                        if (errMsg != string.Empty)
                        {
                            Error.Throw(errMsg);
                        }
                        Columns = ColumnSchema.GetColumns(typeInfo);
                        ConnBean connBean = ConnBean.Create(conn);//下面指定链接,才不会在主从备时被切换到其它库。
                        if (!DBTool.ExistsTable(tableName, connBean.ConnString))
                        {
                            DBTool.ErrorMsg = null;
                            if (!DBTool.CreateTable(tableName, Columns, connBean.ConnString))
                            {
                                Error.Throw("SimpleOrmBase :Create Table " + tableName + " Error:" + DBTool.ErrorMsg);
                            }
                        }
                    }
                    else if (isTxtDal)//文本数据库
                    {
                        if (FieldSource != FieldSource.Data)
                        {
                            MDataColumn c2 = ColumnSchema.GetColumns(typeInfo);
                            if (FieldSource == FieldSource.BothOfAll)
                            {
                                Columns.AddRange(c2);
                            }
                            else
                            {
                                Columns = c2;
                            }
                        }
                    }

                    if (Columns != null && Columns.Count > 0)
                    {
                        CacheManage.LocalInstance.Set(key, Columns, 1440, null);
                    }
                }
                else
                {
                    Columns = CacheManage.LocalInstance.Get(key) as MDataColumn;
                }

                _Action = new MAction(Columns.ToRow(tableName), conn);
                if (typeInfo.Name == "SysLogs")
                {
                    _Action.SetAopState(Aop.AopOp.CloseAll);
                }
                else
                {
                    _Action.SetAopState(op);
                }
                _Action.EndTransation();
            }
            catch (Exception err)
            {
                if (typeInfo.Name != "SysLogs")
                {
                    Log.Write(err, LogType.DataBase);
                }
                throw;
            }
        }
示例#16
0
        /// <summary>
        /// 验证基础数据(数据类型、长度、是否为Null)
        /// </summary>
        /// <returns></returns>
        public static bool ValidateData(MDataTable dt, MDataRow info)
        {
            bool result = true;

            string[]      tables       = null;
            List <string> requiredList = new List <string>();//必填项表。

            if (info != null)
            {
                tables = info.Get <string>(Config_Excel.TableNames, string.Empty).Split(',');
                MDataTable dtRequired = GetExcelInfo(info.Get <string>(0));//必填项表。
                if (dtRequired != null && dtRequired.Rows.Count > 0)
                {
                    dtRequired = dtRequired.Select(Config_ExcelInfo.IsRequired + "=1");
                    if (dtRequired != null && dtRequired.Rows.Count > 0)
                    {
                        foreach (var row in dtRequired.Rows)
                        {
                            requiredList.Add(row.Get <string>(Config_ExcelInfo.TableName) + row.Get <string>(Config_ExcelInfo.Field));
                        }
                    }
                }
            }
            else
            {
                tables = dt.TableName.Split(',');
            }
            bool isOK = false;

            foreach (var table in tables)//重置列头。
            {
                MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(table));
                foreach (var cs in dt.Columns)
                {
                    string[] items = cs.ColumnName.Split('.');
                    if (cs.TableName == table)
                    {
                        int index = mdc.GetIndex(items[items.Length - 1]);
                        if (index > -1)
                        {
                            isOK         = true;//至少需要一个列对应上,若没有,则模板错误
                            cs.SqlType   = mdc[index].SqlType;
                            cs.IsCanNull = mdc[index].IsCanNull;
                            if (requiredList.Contains(table + mdc[index].ColumnName))//要求必填
                            {
                                cs.IsCanNull = false;
                            }
                            cs.MaxSize = mdc[index].MaxSize;
                        }
                    }
                }
            }
            if (!isOK)
            {
                return(false);
            }
            foreach (var row in dt.Rows)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var cell in row)
                {
                    if (!string.IsNullOrEmpty(cell.Struct.TableName))
                    {
                        string columnName = string.IsNullOrEmpty(cell.Struct.Description) ? cell.Struct.ColumnName : cell.Struct.Description;
                        if (!cell.Struct.IsCanNull && cell.IsNullOrEmpty)
                        {
                            sb.AppendFormat("[{0}]{1}", columnName, LangConst.CantBeEmpty);
                            cell.State = -1;
                        }
                        else if (cell.Struct.MaxSize != -1 && cell.ToString().Length > cell.Struct.MaxSize && cell.Struct.SqlType != System.Data.SqlDbType.Bit)
                        {
                            sb.AppendFormat("[{0}]{1}{2}。", columnName, LangConst.SizeOver, cell.Struct.MaxSize);
                            cell.State = -1;
                        }
                        else if (!cell.FixValue())
                        {
                            sb.AppendFormat("[{0}]{1}。", columnName, LangConst.DataTypeError);
                            cell.State = -1;
                        }
                    }
                }
                if (sb.Length > 0)
                {
                    result = false;
                    row.Set(LangConst.ErrorInfo, row.Get <string>(LangConst.ErrorInfo) + sb.ToString());
                }
            }
            return(result);
        }
示例#17
0
        private static void FillTable(string objName, string objCode, MDataTable dt)
        {
            //Dictionary<string, string> fieldTitleDic = GridConfig.FieldTitle;
            string      errInfo;
            string      tableName = objCode;
            MDataColumn mdc       = DBTool.GetColumns(tableName, null, out errInfo);

            if (mdc == null || mdc.Count == 0)
            {
                if (!string.IsNullOrEmpty(errInfo))
                {
                    dt.DynamicData = errInfo;
                }
                return;
            }
            MCellStruct cell = null;
            int         jointPrimaryCount = mdc.JointPrimary.Count;

            for (int i = 0; i < mdc.Count; i++)
            {
                cell = mdc[i];
                MDataRow row = dt.NewRow();
                row.Set(Config_Grid.ObjName, objName);
                row.Set(Config_Grid.Field, cell.ColumnName);
                row.Set(Config_Grid.Title, string.IsNullOrEmpty(cell.Description) ? cell.ColumnName : cell.Description);
                row.Set(Config_Grid.Hidden, (i == 0 && jointPrimaryCount < 2) || i > 25);//超过25个字段,后面的都先隐藏。
                row.Set(Config_Grid.OrderNum, (i + 1) * 10);
                row.Set(Config_Grid.Width, 100);
                row.Set(Config_Grid.Sortable, i > 0);
                row.Set(Config_Grid.Import, i > 0);
                row.Set(Config_Grid.Export, i > 0);
                row.Set(Config_Grid.Colspan, 1);
                row.Set(Config_Grid.Rowspan, 1);
                row.Set(Config_Grid.Edit, i > 0 || jointPrimaryCount > 1);
                row.Set(Config_Grid.Frozen, i < 4);
                row.Set(Config_Grid.Align, "center");
                string value = DataType.GetType(cell.SqlType).Name.ToLower() + "," + cell.MaxSize + "," + cell.Scale + (cell.IsCanNull ? ",0" : ",1") + (cell.IsPrimaryKey ? ",1" : ",0");
                row.Set(Config_Grid.DataType, value);
                if (i == 0)
                {
                    if (jointPrimaryCount < 2)
                    {
                        row.Set(Config_Grid.Formatter, "#");
                    }
                }
                else
                {
                    switch (DataType.GetGroup(cell.SqlType))
                    {
                    case 2:
                        row.Set(Config_Grid.Formatter, "dateFormatter");
                        break;

                    case 3:
                        row.Set(Config_Grid.Formatter, "boolFormatter");
                        break;

                    default:
                        if (cell.MaxSize > 50)
                        {
                            row.Set(Config_Grid.Formatter, "stringFormatter");
                        }
                        break;
                    }
                }
                dt.Rows.Add(row);
            }
        }
示例#18
0
        /// <summary>
        /// 读取数据库所有表
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="filter">过滤条件值</param>
        /// <returns></returns>
        public static MDataTable Get(string key, string filter)
        {
            MDataTable dt = null;
            SortedDictionary <string, string> newDic = new SortedDictionary <string, string>();

            switch (key)
            {
            case "C_SYS_Table":
                if (!string.IsNullOrEmpty(filter))      // 有过滤条件
                {
                    string[] items = filter.Split(','); //指定数据库链接条件
                    foreach (string item in items)
                    {
                        if (item.EndsWith("Conn"))    //当成链接处理
                        {
                            int dbHash = DBInfo.GetHashCode(item);
                            if (DBTool.DataBases.ContainsKey(dbHash))
                            {
                                foreach (var table in DBTool.DataBases[dbHash].Tables)
                                {
                                    newDic.Add(table.Value.Name, table.Value.Name);
                                }
                            }
                        }
                        else    //当成普通表名处理
                        {
                            newDic.Add(item, item);
                        }
                    }
                }
                else
                {
                    foreach (var db in DBTool.DataBases)
                    {
                        foreach (var table in db.Value.Tables)
                        {
                            newDic.Add(table.Value.Name, table.Value.Name);
                        }
                    }
                }
                break;

            case "C_SYS_Column":
                if (!string.IsNullOrEmpty(filter))
                {
                    dt = new MDataTable(key);
                    dt.Columns.Add("value");
                    dt.Columns.Add("text");
                    dt.Columns.Add("parent");
                    string[] items = filter.Split(',');
                    foreach (string item in items)
                    {
                        MDataColumn mdc = DBTool.GetColumns(item);
                        foreach (MCellStruct ms in mdc)
                        {
                            dt.NewRow(true).Set(0, ms.ColumnName).Set(1, ms.ColumnName).Set(2, item);
                        }
                    }
                }

                break;
            }
            if (dt == null)
            {
                dt = MDataTable.CreateFrom(newDic);
                dt.Columns[0].ColumnName = "value";
                dt.Columns[1].ColumnName = "text";
                if (dt.Columns.Count > 2)
                {
                    dt.Columns[2].ColumnName = "parent";
                }
            }
            return(dt);
        }
示例#19
0
        static void Start()
        {
            bool result = DBTool.TestConn(AppConfig.DB.DefaultConn);//检测数据库链接是否正常

            OutMsg("数据库链接:" + result);
            OutMsg("-----------------------------------------");
            string databaseName;
            Dictionary <string, string> tables = DBTool.GetTables(AppConfig.DB.DefaultConn, out databaseName);//读取所有表

            if (tables != null)
            {
                OutMsg("数据库:" + databaseName);
                foreach (KeyValuePair <string, string> item in tables)
                {
                    OutMsg("表:" + item.Key + " 说明:" + item.Value);
                    MDataColumn mdc = DBTool.GetColumns(item.Key);//读取所有列
                    foreach (MCellStruct ms in mdc)
                    {
                        OutMsg("  列:" + ms.ColumnName + " SqlType:" + ms.SqlType);
                    }
                }
            }
            OutMsg("-----------------------------------------");

            string newTableName = "A18";// +DateTime.Now.Second;

            DalType dalType;

            result = DBTool.ExistsTable(newTableName, AppConfig.DB.DefaultConn, out dalType);//检测表是否存在
            OutMsg("表 " + newTableName + (result ? "存在" : "不存在") + " 数据库类型:" + dalType);

            OutMsg("-----------------------------------------");
            if (result)
            {
                result = DBTool.DropTable(newTableName);
                OutMsg("表 " + newTableName + " 删除?" + result);
                OutMsg("-----------------------------------------");
            }

            MDataColumn newMdc = new MDataColumn();

            newMdc.Add("ID", System.Data.SqlDbType.Int);
            newMdc.Add("Name", System.Data.SqlDbType.NVarChar);

            result = DBTool.CreateTable(newTableName, newMdc);
            OutMsg("表 " + newTableName + " 创建?" + result);
            OutMsg("-----------------------------------------");

            newMdc[1].ColumnName = "UserName";
            newMdc[1].AlterOp    = AlterOp.Rename;   //将新创建的表name => username
            newMdc.Add("Password");
            newMdc[2].AlterOp = AlterOp.AddOrModify; // 新增列 Password

            result = DBTool.AlterTable(newTableName, newMdc);
            OutMsg("表 " + newTableName + " 修改结构?" + result);
            OutMsg("-----------------------------------------");

            OutMsg("------------------其它操作-------------------");
            dalType = DBTool.GetDalType("txt path={0}");
            OutMsg("数据库类型为: " + dalType);
            OutMsg("-----------------------------------------");

            OutMsg(DBTool.Keyword("表关键字", DalType.MsSql));//DBTool.NotKeyword 则取消
            OutMsg(DBTool.Keyword("表关键字", DalType.Oracle));
            OutMsg(DBTool.Keyword("表关键字", DalType.MySql));
            OutMsg(DBTool.Keyword("表关键字", DalType.SQLite));

            string changeDataType = DBTool.GetDataType(newMdc[0], DalType.Access, string.Empty);

            OutMsg("数据类型为: " + changeDataType);
            OutMsg("-----------------------------------------");

            string formatValue = DBTool.FormatDefaultValue(DalType.Access, "[#GETDATE]", 1, System.Data.SqlDbType.DateTime);

            OutMsg("Access的日期数据类型为: " + formatValue);
            OutMsg("-----------------------------------------");
        }
示例#20
0
        private static void BuildSingTableEntityText(string tableName, string description, ProjectConfig config, string dbName)
        {
            string str = FormatKey(tableName);

            if (config.MapName)
            {
                str = FixName(tableName);
            }
            bool flag = config.BuildMode.StartsWith("纯") || config.BuildMode.Contains("DBFast");

            try
            {
                StringBuilder sb   = new StringBuilder(50000);
                string        str2 = string.Format(config.NameSpace, dbName + "DB").TrimEnd(new char[] { '.' });
                AppendText(sb, "using System;", new string[0]);
                AppendText(sb, "using System.ComponentModel.DataAnnotations;", new string[0]);
                AppendText(sb, "using System.ComponentModel;", new string[0]);
                if (!config.ForTwoOnly)
                {
                    AppendText(sb, "using System.ComponentModel.DataAnnotations.Schema;", new string[0]);
                }
                AppendText(sb, "", new string[0]);
                AppendText(sb, "namespace {0}", new string[] { str2 });
                AppendText(sb, "{", new string[0]);

                if (!string.IsNullOrEmpty(description))
                {
                    description = description.Replace("\r\n", "    ").Replace("\r", "  ").Replace("\n", "  ");
                    AppendText(sb, "    /// <summary>", new string[0]);
                    AppendText(sb, "    /// {0}", new string[] { description });
                    AppendText(sb, "    /// </summary>", new string[0]);
                    AppendText(sb, "    [DisplayName(\"{0}\")]", new string[] { description });//实体表名的指定方法不是这样操作的,需更新,有空再更新
                }
                if (!config.ForTwoOnly)
                {
                    AppendText(sb, "    [Table(\"{0}\")]", str);
                }
                AppendText(sb, "    public class {0}{1}", new string[] { str + config.EntitySuffix, flag ? "" : " : CYQ.Data.Orm.OrmBase" });
                AppendText(sb, "    {", new string[0]);
                if (!flag)//如果是ORM,则进行下面的生成
                {
                    AppendText(sb, "        public {0}()", new string[] { str + config.EntitySuffix });
                    AppendText(sb, "        {", new string[0]);
                    AppendText(sb, "            base.SetInit(this, \"{0}\", \"{1}\");", new string[] { tableName, config.Name });
                    AppendText(sb, "        }", new string[0]);
                }
                MDataColumn columns = DBTool.GetColumns(tableName, config.Conn);
                if (columns.Count > 0)
                {
                    string name = string.Empty;
                    Type   type = null;

                    if (config.ForTwoOnly) // vs2015 模式
                    {
                        foreach (MCellStruct struct2 in columns)
                        {
                            name = struct2.ColumnName;
                            if (config.MapName)
                            {
                                name = FixName(name);
                            }
                            type = DataType.GetType(struct2.SqlType);
                            string typename = FormatType(type.Name, type.IsValueType, config.ValueTypeNullable);
                            // 详细描述
                            string Longhand_Description = struct2.Description
                                                          #region Longhand_Description 处理
                                                          .Replace("\r\n", "        /// ")
                                                          .Replace("\r", "        /// ")
                                                          .Replace("\n", "        /// ")
                                                          .Replace("        /// ", "\r\n        /// ")
                            ;    //移除回车等换行字符串

                            if (string.IsNullOrEmpty(Longhand_Description))
                            {
                                Longhand_Description = "[ 无说明描术 ]";
                            }
                            #endregion
                            // 名称简写
                            string Shorthand_Description = struct2.Description;
                            #region Shorthand_Description 处理
                            if (string.IsNullOrEmpty(Shorthand_Description))
                            {
                                Shorthand_Description = "[ 无说明描术 ]";
                            }
                            else
                            {
                                Shorthand_Description = Shorthand_Description.Replace("\r\n", "    ").Replace("\r", "  ").Replace("\n", "  ");

                                #region //  从零字符开始,取到指定标志字符处
                                int index = Shorthand_Description.IndexOfAny(new char[] { '(', '(', ':', ':', ' ', ' ', ',', ',', '|', '|', '.', '。' });
                                index = index == -1 ? Shorthand_Description.Length : index;
                                Shorthand_Description = Shorthand_Description.Substring(0, index);
                                #endregion
                            }
                            #endregion

                            AppendText(sb, "        #region [  public     {0} {1} {2}  ]", new string[] { typename.PadRight(15), name.PadRight(30), Shorthand_Description.PadRight(30) });//添加换行

                            AppendText(sb, "        /// <summary>", new string[0]);
                            AppendText(sb, "        /// 私有变量:{0}", new string[] { Longhand_Description });
                            AppendText(sb, "        /// </summary>", new string[0]);
                            AppendText(sb, "        private {0} _{1};", new string[] { typename, name });

                            AppendText(sb, "        /// <summary>", new string[0]);
                            AppendText(sb, "        /// {0}", new string[] { Longhand_Description });
                            AppendText(sb, "        /// </summary>", new string[0]);
                            AppendText(sb, "        [Display(Name = \"{0}\")]", new string[] { Shorthand_Description });
                            AppendText(sb, "        public {0} {1}", new string[] { typename, name });
                            AppendText(sb, "        {", new string[0]);
                            AppendText(sb, "            get", new string[0]);
                            AppendText(sb, "            {", new string[0]);
                            AppendText(sb, "                return _{0};", new string[] { name });
                            AppendText(sb, "            }", new string[0]);
                            AppendText(sb, "            set", new string[0]);
                            AppendText(sb, "            {", new string[0]);
                            AppendText(sb, "                _{0} = value;", new string[] { name });
                            AppendText(sb, "            }", new string[0]);
                            AppendText(sb, "        }", new string[0]);
                            AppendText(sb, "        #endregion", new string[0]);//添加换行
                        }
                    }
                    else // 新模式
                    {
                        foreach (MCellStruct struct3 in columns)
                        {
                            name = struct3.ColumnName;
                            if (config.MapName)
                            {
                                name = FixName(name);
                            }
                            type = DataType.GetType(struct3.SqlType);
                            if (!string.IsNullOrEmpty(struct3.Description))
                            {
                                // 详细描述
                                string Longhand_Description = struct3.Description
                                                              #region Longhand_Description 处理
                                                              .Replace("\r\n", "        /// ")
                                                              .Replace("\r", "        /// ")
                                                              .Replace("\n", "        /// ")
                                                              .Replace("        /// ", "\r\n        /// ")
                                ;    //移除回车等换行字符串

                                if (string.IsNullOrEmpty(Longhand_Description))
                                {
                                    Longhand_Description = "[ 无说明描术 ]";
                                }
                                #endregion
                                // 名称简写
                                string Shorthand_Description = struct3.Description;
                                #region Shorthand_Description 处理
                                if (string.IsNullOrEmpty(Shorthand_Description))
                                {
                                    Shorthand_Description = "[ 无说明描术 ]";
                                }
                                else
                                {
                                    Shorthand_Description = Shorthand_Description.Replace("\r\n", "    ").Replace("\r", "  ").Replace("\n", "  ");

                                    #region //  从零字符开始,取到指定标志字符处
                                    int index = Shorthand_Description.IndexOfAny(new char[] { '(', '(', ':', ':', ' ', ' ', ',', ',', '|', '|', '.', '。' });
                                    index = index == -1 ? Shorthand_Description.Length : index;
                                    Shorthand_Description = Shorthand_Description.Substring(0, index);
                                    #endregion
                                }
                                #endregion

                                struct3.Description = struct3.Description.Replace("\r\n", "    ").Replace("\r", "  ").Replace("\n", "  ");
                                AppendText(sb, "        /// <summary>", new string[0]);
                                AppendText(sb, "        /// {0}", new string[] { Longhand_Description });
                                AppendText(sb, "        /// </summary>", new string[0]);
                                AppendText(sb, "        [Display(Name = \"{0}\")]", new string[] { Shorthand_Description });
                            }
                            if (name.ToUpper() == "ID")
                            {
                                AppendText(sb, "        [DataObjectField(true)]");
                            }
                            AppendText(sb, "        public {0} {1} {{ get; set; }}", new string[] { FormatType(type.Name, type.IsValueType, config.ValueTypeNullable), name });
                            AppendText(sb, "");
                        }
                    }
                }
                sb.Append(
                    @"    }
}");
                File.WriteAllText(config.ProjectPath.TrimEnd(new char[] { '/', '\\' }) + @"\" + str + ".cs", sb.ToString(), Encoding.UTF8);
            }
            catch (Exception exception)
            {
                CYQ.Data.Log.WriteLogToTxt(exception);
            }
        }
示例#21
0
        /// <summary>
        /// 读取数据库所有表
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="filter">过滤条件值</param>
        /// <returns></returns>
        public static MDataTable Get(string key, string filter)
        {
            MDataTable dt = null;
            SortedDictionary <string, string> newDic = new SortedDictionary <string, string>();

            switch (key)
            {
            case "C_SYS_Table":
                if (!string.IsNullOrEmpty(filter))     // 有过滤条件
                {
                    string[] items = filter.Split(',');

                    if (items.Length == 1 && items[0].EndsWith("Conn"))
                    {
                        if (CrossDb.DbTables.ContainsKey(filter))
                        {
                            foreach (var item in CrossDb.DbTables[filter])
                            {
                                newDic.Add(item.Key, item.Key);
                            }
                        }
                    }
                    else
                    {
                        foreach (string item in items)
                        {
                            newDic.Add(item, item);
                        }
                    }
                }
                else
                {
                    foreach (var tableDic in CrossDb.DbTables)
                    {
                        foreach (var item in tableDic.Value)
                        {
                            newDic.Add(item.Key, item.Key);
                        }
                    }
                }
                break;

            case "C_SYS_Column":
                if (!string.IsNullOrEmpty(filter))
                {
                    dt = new MDataTable(key);
                    dt.Columns.Add("value");
                    dt.Columns.Add("text");
                    dt.Columns.Add("parent");
                    string[] items = filter.Split(',');
                    foreach (string item in items)
                    {
                        MDataColumn mdc = DBTool.GetColumns(CrossDb.GetEnum(item));
                        foreach (MCellStruct ms in mdc)
                        {
                            dt.NewRow(true).Set(0, ms.ColumnName).Set(1, ms.ColumnName).Set(2, item);
                        }
                    }
                }

                break;
            }
            if (dt == null)
            {
                dt = MDataTable.CreateFrom(newDic);
                dt.Columns[0].ColumnName = "value";
                dt.Columns[1].ColumnName = "text";
                if (dt.Columns.Count > 2)
                {
                    dt.Columns[2].ColumnName = "parent";
                }
            }
            return(dt);
        }
示例#22
0
        /// <summary>
        /// 初始化状态[继承此基类的实体在构造函数中需调用此方法]
        /// </summary>
        /// <param name="entityInstance">实体对象,一般写:this</param>
        /// <param name="tableName">表名,如:Users</param>
        /// <param name="conn">数据链接,单数据库时可写Null,或写默认链接配置项:"Conn",或直接数据库链接字符串</param>
        protected void SetInit(Object entityInstance, string tableName, string conn)
        {
            conn     = string.IsNullOrEmpty(conn) ? AppConfig.DB.DefaultConn : conn;
            entity   = entityInstance;
            typeInfo = entity.GetType();
            try
            {
                if (string.IsNullOrEmpty(tableName))
                {
                    tableName = typeInfo.Name;
                    if (tableName.EndsWith(AppConfig.EntitySuffix))
                    {
                        tableName = tableName.Substring(0, tableName.Length - AppConfig.EntitySuffix.Length);
                    }
                }

                string key = tableName + MD5.Get(conn);
                if (!CacheManage.LocalInstance.Contains(key))
                {
                    DalType dal      = DBTool.GetDalType(conn);
                    bool    isTxtDal = dal == DalType.Txt || dal == DalType.Xml;
                    string  errMsg   = string.Empty;
                    Columns = DBTool.GetColumns(tableName, conn, out errMsg);//内部链接错误时抛异常。
                    if (Columns == null || Columns.Count == 0)
                    {
                        if (errMsg != string.Empty)
                        {
                            Error.Throw(errMsg);
                        }
                        Columns = TableSchema.GetColumns(typeInfo);
                        if (!DBTool.ExistsTable(tableName, conn))
                        {
                            if (!DBTool.CreateTable(tableName, Columns, conn))
                            {
                                Error.Throw("Create Table Error:" + tableName);
                            }
                        }
                    }
                    else if (isTxtDal)//文本数据库
                    {
                        if (FieldSource != FieldSource.Data)
                        {
                            MDataColumn c2 = TableSchema.GetColumns(typeInfo);
                            if (FieldSource == FieldSource.BothOfAll)
                            {
                                Columns.AddRange(c2);
                            }
                            else
                            {
                                Columns = c2;
                            }
                        }
                    }

                    if (Columns != null && Columns.Count > 0)
                    {
                        CacheManage.LocalInstance.Add(key, Columns, null, 1440);
                    }
                }
                else
                {
                    Columns = CacheManage.LocalInstance.Get(key) as MDataColumn;
                }

                action = new MAction(Columns.ToRow(tableName), conn);
                if (typeInfo.Name == "SysLogs")
                {
                    action.SetAopOff();
                }
                action.EndTransation();
            }
            catch (Exception err)
            {
                if (typeInfo.Name != "SysLogs")
                {
                    Log.WriteLogToTxt(err);
                }
                throw;
            }
        }