Example #1
0
        /// <summary>
        /// 创建类实体文件
        /// </summary>
        /// <param name="table">数据表实体</param>
        /// <param name="codeEntParam">实体参数</param>
        public void CreateCodeFile(Table table, CodeEntityParameter codeEntParam)
        {
            string className = string.Empty;
            CodeDomHelper codeDomHelper = new CodeDomHelper();

            className = GetClassName(table, codeEntParam);
            var codeCompileUnit = codeDomHelper.GetCodeCompileUnit(codeEntParam.NameSpace, className, string.IsNullOrWhiteSpace(table.Comment) ? table.Name : table.Comment);
            var codeTypeDeclaration = codeCompileUnit.Namespaces[0].Types[0];
            foreach (var column in table.Columns)
            {
                codeTypeDeclaration.Members.Add(codeDomHelper.CreateAutoProperty(column.Type, column.Name, column.Comment));
            }

            CodeDomProvider provider = new CSharpCodeProvider();
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";
            var stringBuilder = new StringBuilder();
            using (provider)
            {
                var stringWriter = new StringWriter(stringBuilder);
                provider.GenerateCodeFromCompileUnit(codeCompileUnit, stringWriter, new CodeGeneratorOptions());
            }
            string tmpPath = string.IsNullOrWhiteSpace(codeEntParam.Suffix) ? "Entity" : codeEntParam.Suffix;
            string path = codeEntParam.SavePath;
            if (! codeEntParam.SavePath.EndsWith(tmpPath))
            {
                path = Path.Combine(codeEntParam.SavePath, tmpPath);
            }

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                string filePath = Path.Combine(path, className + ".cs");
                File.WriteAllText(filePath, CleanupCode(stringBuilder.ToString()), Encoding.UTF8);
            }
            catch (IOException ioEx)
            {
                throw ioEx;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #2
0
        public IList<Table> GetTables()
        {
            string sql = @"select a.object_id as ID, a.name as Name, b.value as Comment from sys.tables a
            left join sys.extended_properties b on a.object_id = b.major_id and minor_id =0
            inner join sys.tables c on a.object_id = c.object_id";

            DataTable dt = DBUtil.GetDataTable(connStr, sql);
            List<Table> list = new List<Table>();
            foreach (DataRow row in dt.Rows)
            {
                Table table = new Table();
                table.ID = row["ID"].ToString();
                table.Name = row["Name"].ToString();
                table.Comment = row["Comment"].ToString();

                list.Add(table);
            }

            return list;
        }
Example #3
0
        public IList<Column> GetColumns(Table table)
        {
            string sql = string.Format(@"
            WITH colConsCTE(TABLE_NAME, COLUMN_NAME, CONSTRAINT_TYPE) AS (
             SELECT A.TABLE_NAME, A.COLUMN_NAME, B.CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE A
             LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS B ON A.CONSTRAINT_NAME = B.CONSTRAINT_NAME AND A.TABLE_NAME = B.TABLE_NAME
            )
            SELECT a.object_id AS TableID, a.name AS TableName, b.column_id AS ID, b.name as Name, d.value AS Comment , c.name AS DBType, b.max_length AS 'Length',
            CASE WHEN (SELECT COUNT(1) FROM colConsCTE cte WHERE b.name = cte.COLUMN_NAME AND a.name = cte.TABLE_NAME AND cte.CONSTRAINT_TYPE ='PRIMARY KEY') > 0 THEN 1 ELSE 0 END AS IsPrimaryKey,
            CASE WHEN (SELECT COUNT(1) FROM colConsCTE cte WHERE b.name = cte.COLUMN_NAME AND a.name = cte.TABLE_NAME AND cte.CONSTRAINT_TYPE ='FOREIGN KEY') > 0 THEN 1 ELSE 0 END AS IsForeignKey,
            b.IS_NULLABLE as 'IsNullAble'
            FROM sys.tables a
            LEFT JOIN sys.columns b on a.object_id = b.object_id
            LEFT JOIN sys.types c on b.user_type_id = c.user_type_id
            LEFT JOIN sys.extended_properties d on a.object_id = d.major_id and d.minor_id = b.column_id
            WHERE a.name='{0}'", table.Name);

            DataTable dt = DBUtil.GetDataTable(connStr, sql);
            List<Column> list = new List<Column>();
            foreach (DataRow row in dt.Rows)
            {
                Column column = new Column();
                column.ID = row["ID"].ToString();
                column.Name = row["Name"].ToString();
                column.Comment = row["Comment"].ToString();
                column.DBType = row["DBType"].ToString();
                column.IsPrimaryKey = row["IsPrimaryKey"].ToString() == "1";
                column.IsForeignKey = row["IsForeignKey"].ToString() == "1";
                column.IsNullAble = bool.Parse(row["IsNullAble"].ToString());
                column.Table = table;
                list.Add(column);
            }

            table.Columns = list;

            return list;
        }
Example #4
0
        /// <summary>
        /// 获取数据表对应的类名
        /// </summary>
        /// <param name="table">数据表实体</param>
        /// <param name="codeEntParam">实体参数</param>
        /// <returns>类名</returns>
        private string GetClassName(Table table, CodeEntityParameter codeEntParam)
        {
            string className = table.Name;
            if (codeEntParam.IsAddOrRemovePrefix)
            {
                if (! table.Name.StartsWith(codeEntParam.Prefix))
                {
                    className = string.Format("{0}{1}", codeEntParam.Prefix, table.Name);
                }
            }
            else
            {
                if (table.Name.StartsWith(codeEntParam.Prefix))
                {
                    className = table.Name.Remove(0, codeEntParam.Prefix.Count());
                }
            }

            if (codeEntParam.IsAddSuffix)
            {
                className = string.Format("{0}{1}", className, codeEntParam.Suffix);
            }

            return className;
        }
Example #5
0
        private void btnGenerateCode_Click(object sender, EventArgs e)
        {
            Table table = new Table();

            if (cboDatabase.SelectedValue == null)
            {
                MessageBox.Show("数据库未选择,未连接数据库?");
                return;
            }
            string dbName = cboDatabase.SelectedValue.ToString();
            CodeEntityDataReader entDataReader = new CodeEntityDataReader(GetConnStr(dbName));

            table = lstTable.SelectedItem as Table;
            if (table == null)
            {
                MessageBox.Show("未选择要生成的数据表");
                return;
            }
            string tableName = table.Name;
            List<Table> tableList = entDataReader.GetTables().ToList();

            table = tableList.FirstOrDefault(m => m.Name == tableName);
            entDataReader.GetColumns(table);

            CodeEntityParameter entParam = GetEntityParameter();

            CodeGenerator.Core.CodeGenerator code = new CodeGenerator.Core.CodeGenerator();
            code.CreateCodeFile(table, entParam);

            MessageBox.Show("生成成功!");
        }