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

代码生成器源码

时间:2015-01-28 23:57:18      阅读:493      评论:0      收藏:0      [点我收藏+]

标签:

xmal文件

<Window x:Class="MyCode.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="代码生成器" Height="650" Width="825" Loaded="Window_Loaded"
        WindowStartupLocation="CenterScreen">
    <Grid>
        <TextBox Name="txtConnStr" HorizontalAlignment="Left" Height="23" Margin="20,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="647"/>
        <Button Name="btnConnect" Content="连接" HorizontalAlignment="Left" Margin="699,10,0,0" VerticalAlignment="Top" Width="108" Click="btnConnect_Click"/>
        <ComboBox Name="cmbTables"  IsEnabled="False" HorizontalAlignment="Left" Margin="20,51,0,0" VerticalAlignment="Top" Width="222"/>
        <Button Name="btnCodeGen" IsEnabled="False"  Content="生成代码" HorizontalAlignment="Left" Margin="285,53,0,0" VerticalAlignment="Top" Width="98" RenderTransformOrigin="0.587,0.158" Click="btnCodeGen_Click"/>
        <TextBox Name="txtModel" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" IsReadOnly="True" HorizontalAlignment="Left" Height="509" Margin="20,90,0,0"  Text="" VerticalAlignment="Top" Width="328"/>
        <TextBox Name="txtDAL" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" IsReadOnly="True" HorizontalAlignment="Left" Height="509" Margin="370,90,0,0"  Text="" VerticalAlignment="Top" Width="437"/>

    </Grid>
</Window>

 cs文件

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MyCode
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public DataTable ExecuteDataTable(string sql)
        {
            using(SqlConnection conn=new SqlConnection(txtConnStr.Text))
            {
                    conn.Open();
                    using(SqlCommand cmd=conn.CreateCommand())
                    {
                        cmd.CommandText = sql;
                        DataSet ds = new DataSet();
                        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                        adapter.FillSchema(ds, SchemaType.Source);
                        adapter.Fill(ds);
                        return ds.Tables[0];
                    }
             }
        }
        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            if(txtConnStr.Text.Length>0)
            {
                //选出所有的表名
                string sql = "select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=‘BASE TABLE‘";
                DataTable table = null ;
                try
                {
                    table = ExecuteDataTable(sql);
                }
                catch(SqlException sqlex)
                {
                    MessageBox.Show("连接数据库出错:"+sqlex.Message);
                }
                string[] tables = new string[table.Rows.Count];
                for(int i=0;i<table.Rows.Count;++i)
                {
                    DataRow row = table.Rows[i];
                    tables[i] = (string)row[0];

                }
                cmbTables.ItemsSource = tables;
                cmbTables.IsEnabled = true;
                btnCodeGen.IsEnabled = true;

                //把连接字符串记录到文件中,方便下次链接

                string configFile = GetConfigFilePath();
                //写入文件
                File.WriteAllText(configFile, txtConnStr.Text);
            }
            else
            {
                MessageBox.Show("请输入连接字符串!");
            }
        }

        public string GetConfigFilePath()
        {
            string configDir = AppDomain.CurrentDomain.BaseDirectory;
            string configFile = System.IO.Path.Combine(configDir, "configFile.txt");
            if(!File.Exists(configFile))//如果不存在创建之
            {
                using (FileStream fs = File.Create(configFile)) { }
            }
            return configFile;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string configFile=GetConfigFilePath();
            txtConnStr.Text = File.ReadAllText(configFile);
        }

        private string GetDataType(DataColumn colum)
        {
            if (colum.AllowDBNull && colum.DataType.IsValueType )
            {
                return colum.DataType + "?";
            }
            else return colum.DataType.ToString();
        }
        private void btnCodeGen_Click(object sender, RoutedEventArgs e)
        {
            
            string tableName = (string)cmbTables.SelectedItem;
            if(tableName==null)
            {
                MessageBox.Show("请先选择表!");
                return;
            }
            CreateModelCode(tableName);
            CreateDALCode(tableName);
        }
        private void CreateModelCode(string tableName)
        {
            string sql = "select top 0 * from " + tableName;
            DataTable table = ExecuteDataTable(sql);
            StringBuilder sb = new StringBuilder();
            sb.Append("public class ").Append(tableName).AppendLine(" {");
            
            foreach (DataColumn colum in table.Columns)
            {
                string dataType = GetDataType(colum);
                sb.Append("public ").Append(dataType).Append(" ").Append(colum.ColumnName).AppendLine("{ get ; set ; }");

            }
            sb.AppendLine("}");
            txtModel.Text = sb.ToString();
        }
        private void CreateDALCode(string tableName)
        {
            string sql = "select top 0 * from " + tableName;
            DataTable table = ExecuteDataTable(sql);
            
            StringBuilder sb = new StringBuilder();
            sb.Append("public class ").Append(tableName).AppendLine("DAL");
            sb.AppendLine("{");
            //类的内部方法
        //方法1
        //    public object ToDBNull(object value)
        //  {
        //    if(value==null)
        //    {
        //        return DBNull.Value;
        //    }
        //    else
        //    {
        //        return value;
        //    }
        //  }
            sb.AppendLine();
            sb.AppendLine("private object ToDBNull(object value) ");
            sb.AppendLine("{");
            sb.AppendLine("if(value==null) { return DBNull.Value; }");
            sb.AppendLine("else { return value; }");
            sb.AppendLine("}");
            sb.AppendLine();



            //方法2
        //    public object FromDBNull(object value)
        //{
        //    if(value==DBNull.Value)
        //    {
        //        return null;
        //    }
        //    else
        //    {
        //        return value;
        //    }
        //}
            sb.AppendLine();
            sb.AppendLine("private object FromDBNull(object value) ");
            sb.AppendLine("{");
            sb.AppendLine("if(value==DBNull.Value) { return null; }");
            sb.AppendLine("else { return value; }");
            sb.AppendLine("}");
            sb.AppendLine();

            //方法3
            //DataRowToModel
            sb.AppendLine();
            sb.Append("private ").Append(tableName).Append(" DataRowToModel(DataRow row)");
            sb.AppendLine("{");
            sb.Append(tableName).Append(" model = new ").Append(tableName).AppendLine("() ;");
            foreach(DataColumn column in table.Columns)
            {
                // employee.HomePlace = (string)row["HomePlace"];
                string dataType=GetDataType(column);
                if (column.AllowDBNull && column.DataType.IsValueType)
                {
                    sb.Append("model.").Append(column.ColumnName).Append(" = (").Append(dataType).Append(")FromDBNull( row[\"").Append(column.ColumnName).AppendLine("\"]);");
                }
                else
                {
                    sb.Append("model.").Append(column.ColumnName).Append(" = (").Append(dataType).Append(") row[\"").Append(column.ColumnName).AppendLine("\"];");
                }
                
            }
            sb.AppendLine("return model;");
            sb.AppendLine("}");
            sb.AppendLine();


            //方法4
        //    public Employee GetById(Guid id)
        //{
        //    string sql = "select * from T_Employee where ID=@ID";
        //    Employee employee = new Employee();
        //    DataTable table = SqlHelper.ExecuteDataTable(sql, new SqlParameter("@ID", id));
        //    if(table.Rows.Count<=0)
        //    {
        //        MessageBox.Show("未找到相关记录");
        //        return null;
        //    }
        //    else if(table.Rows.Count>1)
        //    {
        //        throw new Exception("主键重复");
        //    }
        //    else
        //    {
        //        employee = DataRowToEmployee(table.Rows[0]);
        //        return employee;
        //    }
        //}
            sb.AppendLine();
            sb.Append("public ").Append(tableName).Append(" GetById(").Append(GetDataType(table.PrimaryKey[0]).ToString()).AppendLine(" id)");
            sb.AppendLine("{");
            sb.Append("string sql = \"select * from ").Append(tableName).AppendLine(" where ID=@ID\" ;");
            sb.Append(tableName).Append(" model = new ").Append(tableName).AppendLine("() ;");
            sb.AppendLine("DataTable table = SqlHelper.ExecuteDataTable(sql, new SqlParameter(\"@ID\", id));");
            sb.AppendLine("if(table.Rows.Count<=0) { MessageBox.Show(\"未找到相关记录\"); return null; }");
            sb.AppendLine("else if(table.Rows.Count>1) { throw new Exception(\"主键重复\"); }");
            sb.AppendLine("else { return model=DataRowToModel(table.Rows[0]); }");
            sb.AppendLine("}");
            sb.AppendLine();



            //方法5
        //    public void DeleteById(Guid id)
        //{
        //    string sql = "update T_User set IsDeleted=1 where ID=@ID";
        //    SqlHelper.ExecuteNonQuery(sql, new SqlParameter("@ID", id));
        //}
            sb.AppendLine();
            sb.Append("public void DeleteById(").Append(GetDataType(table.PrimaryKey[0]).ToString()).AppendLine(" id)");
            sb.AppendLine("{");
            sb.Append("string sql = \"update ").Append(tableName).AppendLine(" set IsDeleted=1  where ID=@ID\" ;");
            sb.AppendLine("SqlHelper.ExecuteNonQuery(sql, new SqlParameter(\"@ID\", id));");
            sb.AppendLine("}");
            sb.AppendLine();



            //方法6
        //     public User[] ListAll()
        //{
            
        //    string sql = "select * from T_User where IsDeleted=0";
        //    DataTable table = SqlHelper.ExecuteDataTable(sql);
        //    User[] users =new User[table.Rows.Count];
        //    for(int i=0;i<table.Rows.Count;++i)
        //    {
        //        users[i] = ToUser(table.Rows[i]);
        //    }
        //    return users;
        //}
            sb.AppendLine();
            sb.Append("public ").Append(tableName).AppendLine("[] ListAll()");
            sb.AppendLine("{");
            sb.Append("string sql = \"select * from ").Append(tableName).AppendLine(" where IsDeleted=0\" ;");
            sb.AppendLine("DataTable table = SqlHelper.ExecuteDataTable(sql);");
            sb.Append(tableName).Append("[] models = new ").Append(tableName).AppendLine(" [table.Rows.Count];");
            sb.AppendLine("for(int i=0;i<table.Rows.Count;++i)");
            sb.AppendLine("{");
            sb.AppendLine("models[i] = DataRowToModel(table.Rows[i]);");
            sb.AppendLine("}");
            sb.AppendLine("return models;");
            sb.AppendLine("}");
            sb.AppendLine();
 



            //方法7
        //    public void Insert(Department depart)
        //{
        //    string sql = "insert into T_Department(ID,Name,IsDeleted) values(newid(),@Name,0)";
        //    SqlHelper.ExecuteNonQuery(sql, new SqlParameter("@Name", depart.Name));
        //}
            string[] columnsNames=GetColumnsName(table);
            string[] paramsNames = GetParamsName(table);
            string[] newParamsStrings=GetNewParamsStrings(table);
            sb.Append("public void Insert( ").Append(tableName).AppendLine(" model)");
            sb.AppendLine("{");
            sb.Append("string sql = @\"insert into ").Append(tableName).Append(" \n(").Append(string.Join(",",columnsNames )).Append(" )\n values\n(").Append(string.Join(",", paramsNames)).AppendLine(" )\";");
            sb.Append("SqlHelper.ExecuteNonQuery(sql, ").AppendLine(string.Join(",", newParamsStrings));
            
            sb.AppendLine(");");
            sb.AppendLine("}");
            sb.AppendLine();
            sb.AppendLine();


            //方法7更新
            //三个参数在增加时已经查出
            //string[] columnsNames = GetColumnsName(table);
            //string[] paramsNames = GetParamsName(table);
            //string[] newParamsStrings = GetNewParamsStrings(table);
            sb.Append("public void Update( ").Append(tableName).AppendLine(" model)");
            sb.AppendLine("{");
            //string sql = "update T_Department set Name=@Name,IsDeleted=@IsDeleted where ID=@ID";

            sb.Append("string sql = @\"update ").Append(tableName).Append(" set ").Append(string.Join(",", GetUpdateStrings(table))).AppendLine(" \";");
            
            sb.Append("SqlHelper.ExecuteNonQuery(sql, ").AppendLine(string.Join(",", newParamsStrings));

            sb.AppendLine(");");
            sb.AppendLine("}");
            sb.AppendLine();
            sb.AppendLine();

            //类的内部方法结束
            sb.AppendLine("}");
            txtDAL.Text = sb.ToString();
        }
        private string[] GetColumnsName(DataTable table)
        {
            string[] names = new string[table.Columns.Count];
            for (int i = 0; i < table.Columns.Count;++i )
            {
                names[i] = table.Columns[i].ColumnName;
            }
            return names;
        }
        private string[] GetParamsName(DataTable table)
        {
            string[] names = new string[table.Columns.Count];
            for (int i = 0; i < table.Columns.Count; ++i)
            {
                names[i] = "@"+table.Columns[i].ColumnName;
            }
            return names;
        }
        private string[]GetNewParamsStrings(DataTable table)
        {
            string[] columnsNames = GetColumnsName(table);
            string[] paramsNames = GetParamsName(table);
            string[] newParamsStrings = new string[table.Columns.Count];
            for(int i=0;i<table.Columns.Count;++i)
            {
                DataColumn column = table.Columns[i];
                if(column.AllowDBNull&&column.DataType.IsValueType)
                {
                    newParamsStrings[i] = "\n new SqlParameter(\"" + paramsNames[i] + "\", ToDBNull(model." + columnsNames[i] + ") )";
                }
                else
                {
                    newParamsStrings[i] = "\n new SqlParameter(\"" + paramsNames[i] + "\", model." + columnsNames[i] + " )";
                }
                
            }
            return newParamsStrings;
        }
        private string[] GetUpdateStrings(DataTable table)
        {
            string[] columnsNames = GetColumnsName(table);
            string[] paramsNames = GetParamsName(table);
            string[] updateStrings = new string[table.Columns.Count];
            for (int i = 0; i < table.Columns.Count; ++i)
            {
                DataColumn column = table.Columns[i];
                updateStrings[i] = "\n "+columnsNames[i] + " = " + paramsNames[i];
            }
            return updateStrings;
        }
    }
}

 

代码生成器源码

标签:

原文地址:http://www.cnblogs.com/I-am-on-the-way/p/4257435.html

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