https://www.cnblogs.com/spring_wang/p/10026107.html
private void btnGenerate_Click(object sender, EventArgs e)
{
folderDialog = new FolderBrowserDialog();
if (folderDialog.ShowDialog() == DialogResult.OK)
{
txtFilePathText = folderDialog.SelectedPath;
}
if (!string.IsNullOrEmpty(txtFilePathText))
{
if (checkModel.Checked || checkDAL.Checked || checkBLL.Checked)
{
GeneratorArgs args = new GeneratorArgs();
args.ConnectionString = txtConnStr.Text;
args.OutputDir = txtFilePathText;
args.RootNamespace = txtNameSpace.Text;
DataTable dtCols = null;
DataRow drCols = null;
foreach (string tablename in clbTables.CheckedItems)
{
dtCols = Generator.GetColsTable(tablename, args);
DataRow[] drs = dtCols.Select("Column_PK=1");
drCols = null;
if (drs != null && drs.Length > 0)
{
drCols = drs[0];
}
if (checkModel.Checked)
{
Generator.GenerateModel(dtCols, drCols, tablename, args);
}
if (checkDAL.Checked)
{
Generator.GenerateDAL(dtCols, drCols, tablename, args);
}
if (checkBLL.Checked)
{
Generator.GenerateBLL(dtCols, drCols, tablename, args);
}
}
ShowMessage("生成成功!請到 " + txtFilePathText + " 目錄中查看..");
}
else
{
ShowMessage("生成失敗:您還未選擇要生成的層!");
}
}
else
{
ShowMessage("生成失敗:您還未選擇要輸出的路徑!");
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.IO;
namespace codeGenerator
{
class Generator
{
public static DataTable ExecuteDataTable(string connStr, string cmdText,
params SqlParameter[] parameters)
{
using (SqlConnection con = new SqlConnection(connStr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(cmdText, con))
{
cmd.Parameters.AddRange(parameters);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
}
}
private static Type GetTypeByDBType(string dataType)
{
Dictionary<string, Type> DbTypeDic = new Dictionary<string, Type>()
{
{ "int", typeof(Int32) },
{ "text", typeof(String) },
{ "bigint", typeof(Int64) },
{ "binary", typeof(byte[]) },
{ "bit", typeof(Boolean) },
{ "char", typeof(String) },
{ "date", typeof(DateTime) },
{ "datetime", typeof(DateTime) },
{ "datetime2", typeof(DateTime) },
{ "decimal", typeof(Decimal) },
{ "float", typeof(Double) },
{ "image", typeof(Byte[]) },
{ "money", typeof(Decimal) },
{ "nchar", typeof(String) },
{ "ntext", typeof(String) },
{ "numeric", typeof(Decimal) },
{ "nvarchar", typeof(String) },
{ "real", typeof(Single) },
{ "smalldatetime", typeof(DateTime) },
{ "smallint", typeof(Int16) },
{ "smallmoney", typeof(Decimal) },
{ "timestamp", typeof(Byte[]) },
{ "tinyint", typeof(Byte) },
{ "varbinary", typeof(Byte[]) },
{ "varchar", typeof(String) },
{ "variant", typeof(Object) },
{ "uniqueidentifier", typeof(Guid) },
};
foreach (KeyValuePair<string, Type> kv in DbTypeDic)
{
if (kv.Key == dataType)
{
return kv.Value;
}
}
return typeof(Object);
}
private static string[] GetCols(DataTable dtCols)
{
List<string> list = new List<string>();
foreach (DataRow row in dtCols.Rows)
{
string colName = Convert.ToString(row["Column_Name"]);
list.Add(colName);
}
return list.ToArray();
}
private static string[] GetColsWithoutId(DataTable dtCols, DataRow drCols)
{
List<string> list = new List<string>();
list.AddRange(GetCols(dtCols));
foreach (string colname in list.ToArray())
{
if (drCols != null && colname.Equals(drCols["Column_Name"].ToString(),
StringComparison.CurrentCultureIgnoreCase))
{
list.Remove(colname);
}
}
return list.ToArray();
}
public static DataTable GetColsTable(string tbName, GeneratorArgs args)
{
DataTable dtCols = ExecuteDataTable(args.ConnectionString,
@"SELECT a.name AS Column_Name,b.name AS Data_Type,convert(varchar, ISNULL(g.[value], '')) AS Column_Des,CASE WHEN EXISTS
(SELECT 1
FROM dbo.sysindexes si INNER JOIN
dbo.sysindexkeys sik ON si.id = sik.id AND si.indid = sik.indid INNER JOIN
dbo.syscolumns sc ON sc.id = sik.id AND sc.colid = sik.colid INNER JOIN
dbo.sysobjects so ON so.name = si.name AND so.xtype = 'PK'
WHERE sc.id = a.id AND sc.colid = a.colid) THEN 1 ELSE 0 END AS Column_PK
FROM dbo.syscolumns a LEFT OUTER JOIN
dbo.systypes b ON a.xtype = b.xusertype INNER JOIN
dbo.sysobjects d ON a.id = d.id AND d.xtype = 'U' AND
d.status >= 0 LEFT OUTER JOIN
dbo.syscomments e ON a.cdefault = e.id LEFT OUTER JOIN
sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id AND
g.name = 'MS_Description' LEFT OUTER JOIN
sys.extended_properties f ON d.id = f.major_id AND f.minor_id = 0 AND
f.name = 'MS_Description'
where d.name=@tablename",
new SqlParameter("tablename", tbName));
return dtCols;
}
public static void GenerateModel(DataTable dtCols, DataRow drCols, string tbName, GeneratorArgs args)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
sb.AppendLine("using System.Text;");
sb.AppendLine("using System.Data;");
sb.AppendLine("using System.Data.SqlClient;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("");
sb.AppendLine("namespace " + args.RootNamespace + ".Model");
sb.AppendLine("{");
sb.AppendLine("partial class " + tbName);
sb.AppendLine("{");
foreach (DataRow row in dtCols.Rows)
{
string colName = row["Column_Name"].ToString();
string colDes = row["Column_Des"].ToString();
string dataType = row["Data_Type"].ToString();
Type dotnetType = GetTypeByDBType(dataType);
string netTypeName;
if (dotnetType.IsValueType)
{
netTypeName = dotnetType.ToString() + "?";
}
else
{
netTypeName = dotnetType.ToString();
}
netTypeName = netTypeName.Replace("System.", string.Empty);
sb.AppendLine("//" + colDes);
sb.AppendLine("public " + netTypeName + " " + colName + " { get; set; }");
}
sb.AppendLine("}");
sb.AppendLine("}");
string modelDir = Path.Combine(args.OutputDir, "Model");
string modelFile =
Path.Combine(modelDir, tbName + ".cs");
Directory.CreateDirectory(modelDir);
File.WriteAllText(modelFile, sb.ToString());
}
public static void GenerateDAL(DataTable dtCols, DataRow drCols, string tablename, GeneratorArgs args)
{
string pknetTypeName = string.Empty;
if (drCols != null)
{
string pkdataType = Convert.ToString(drCols["Data_Type"]);
Type pknetType = GetTypeByDBType(pkdataType);
//處理可空數據類型
if (pknetType.IsValueType)
{
pknetTypeName = pknetType.ToString() + "?";
}
else
{
pknetTypeName = pknetType.ToString();
}
pknetTypeName = pknetTypeName.Replace("System.", string.Empty);
}
StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using System.Linq;");
sb.AppendLine("using System.Text;");
sb.AppendLine("using " + args.RootNamespace + ".Model;");
sb.AppendLine("using System.Data.SqlClient;");
sb.AppendLine("using System.Data;");
sb.AppendLine("");
sb.AppendLine("namespace " + args.RootNamespace + ".DAL");
sb.AppendLine("{");
sb.AppendLine("partial class " + tablename + "DAL");
sb.AppendLine("{");
{
sb.AppendLine("public FCParamter GetItems(" + tablename + " model){");
string[] cols = GetColsWithoutId(dtCols, drCols);
sb.AppendLine("FCParamter fCParamter = new FCParamter();");
if (drCols != null)
{
sb.AppendLine("fCParamter.pk = new SqlParameter(\"" + drCols["Column_Name"].ToString() + "\", model." + drCols["Column_Name"].ToString() + ");");
}
sb.AppendLine("fCParamter.parameters = new SqlParameter[] {");
int i = 0;
foreach (string col in cols)
{
if (i == 0)
{
sb.AppendLine("new SqlParameter(\"" + col + "\", model." + col + ")");
}
else
{
sb.AppendLine(",new SqlParameter(\"" + col + "\", model." + col + ")");
}
i++;
}
sb.AppendLine("};");
sb.AppendLine("return fCParamter;");
sb.AppendLine("}");
sb.AppendLine("public void Insert(" + tablename + " model){");
//string[] colParams = (from col in cols
// select "@" + col).ToArray();
//sb.AppendLine("string sql = \"insert into " + tablename +
// "(" + string.Join(",", cols) +
// ") output inserted.id values(" +
// string.Join(",", colParams) + ")\";");
sb.AppendLine("SqlHelper.ExecuteInsertSql(\"" + tablename + "\",GetItems(model).parameters);");
sb.AppendLine("}");
}
{
sb.AppendLine("public void Update(" + tablename + " model){");
//string[] cols = GetColsWithoutId(dtCols);
//string[] colParams = (from col in cols
// select col + "=@" + col).ToArray();
//sb.AppendLine("string sql = \"update " + tablename + " set " +
// string.Join(",", colParams) + " where id=@id\";");
sb.AppendLine("FCParamter fCParamter = GetItems(model);");
sb.AppendLine("SqlHelper.ExecuteUpdateSql(\"" + tablename + "\",fCParamter.pk, fCParamter.parameters);");
//foreach (string col in GetCols(dtCols))
//{
// sb.AppendLine(",new SqlParameter(\"" + col + "\", model." + col + ")");
//}
sb.AppendLine("}");
}
{
sb.AppendLine("private static " + tablename +
" ToModel(DataRow row){");
sb.AppendLine(tablename + " model = new "
+ tablename + "();");
foreach (DataRow row in dtCols.Rows)
{
string colName = Convert.ToString(row["Column_Name"]);
string dataType = Convert.ToString(row["Data_Type"]);
Type netType = GetTypeByDBType(dataType);
string netTypeName;
//處理可空數據類型
if (netType.IsValueType)
{
netTypeName = netType.ToString() + "?";
}
else
{
netTypeName = netType.ToString();
}
netTypeName = netTypeName.Replace("System.", string.Empty);
sb.AppendLine("model." + colName + " = row.IsNull(\"" + colName + "\")?null:(" +
netTypeName + ")row[\"" + colName + "\"];");
}
sb.AppendLine("return model;}");
}
if (drCols != null)
{
{
sb.AppendLine("public " + tablename + " Get(" + pknetTypeName + " " + drCols["Column_Name"].ToString() + "){");
sb.AppendLine("DataTable dt = SqlHelper.ExecuteDataTable(\"select * from "
+ tablename + " where " + drCols["Column_Name"].ToString() + "=@" + drCols["Column_Name"].ToString() + "\",");
sb.AppendLine("new SqlParameter(\"" + drCols["Column_Name"].ToString() + "\"," + drCols["Column_Name"].ToString() + "));");
sb.AppendLine("if (dt.Rows.Count > 1)");
sb.AppendLine("{throw new Exception(\"more than 1 row was found\");}");
sb.AppendLine("if (dt.Rows.Count <= 0){return null;}");
sb.AppendLine("DataRow row = dt.Rows[0];");
sb.AppendLine(tablename + " model = ToModel(row);");
sb.AppendLine("return model;}");
}
{
sb.AppendLine("public bool RepeatChk(string wherestr, List<SqlParameter> whereParameters, " + pknetTypeName + " " + drCols["Column_Name"].ToString() + ")");
sb.AppendLine("{");
sb.AppendLine("string sql = string.Empty;");
sb.AppendLine("if (" + drCols["Column_Name"].ToString() + " != null)");
sb.AppendLine("{");
sb.AppendLine(" sql = \" select count(1) as rs from " + tablename + " where " + drCols["Column_Name"].ToString() + " <> \" + " + drCols["Column_Name"].ToString() + ".ToString() + \"\" + wherestr;");
sb.AppendLine("}");
sb.AppendLine("else");
sb.AppendLine("{");
sb.AppendLine(" sql = \" select count(1) as rs from " + tablename + " where 1=1\" + wherestr;");
sb.AppendLine("}");
sb.AppendLine("return ((int)SqlHelper.ExecuteScalar(sql, whereParameters.ToArray())) > 0;");
sb.AppendLine("}");
}
}
{
sb.AppendLine("public ResultPageingObject SelectByPage(int pageIndex, int pageSize, string wherestr, string orderby, List<SqlParameter> whereParameters)");
sb.AppendLine("{");
sb.AppendLine(" ResultPageingObject resultPageingObject = new ResultPageingObject();");
sb.AppendLine(" DataSet ds =SqlHelper.SelectByPage(\"" + tablename + "\", 1, 10, wherestr, orderby, whereParameters); ");
sb.AppendLine(" resultPageingObject.dt = ds.Tables[0];");
sb.AppendLine(" resultPageingObject.count = Convert.ToInt32(ds.Tables[1].Rows[0][0]);");
sb.AppendLine(" ds.Tables.RemoveAt(1);");
sb.AppendLine(" return resultPageingObject;");
sb.AppendLine("}");
}
{
sb.AppendLine("public DataTable SelectList(string wherestr, string orderby, List<SqlParameter> whereParameters)");
sb.AppendLine("{");
sb.AppendLine("string extsql = string.Empty;");
sb.AppendLine("if (!string.IsNullOrWhiteSpace(wherestr))");
sb.AppendLine("{");
sb.AppendLine(" extsql += \" where \" + wherestr + \" \";");
sb.AppendLine("}");
sb.AppendLine("if (!string.IsNullOrWhiteSpace(orderby))");
sb.AppendLine("{");
sb.AppendLine(" extsql += \" order by \" + orderby + \" \";");
sb.AppendLine("}");
sb.AppendLine("return SqlHelper.ExecuteDataTable(\"select * from " + tablename + " \" + extsql, whereParameters.ToArray());");
sb.AppendLine("}");
}
{
sb.AppendLine("public List<" + tablename
+ "> SelectLists(string wherestr, string orderby, List<SqlParameter> whereParameters){");
sb.AppendLine("List<" + tablename + "> list = new List<" +
tablename + ">();");
sb.AppendLine("DataTable dt = SelectList(wherestr, orderby, whereParameters);");
sb.AppendLine("foreach (DataRow row in dt.Rows){");
sb.AppendLine("list.Add(ToModel(row));}");
sb.AppendLine("return list;}");
}
sb.AppendLine("}");
sb.AppendLine("}");
string dalDir = Path.Combine(args.OutputDir, "DAL");
string dalFile =
Path.Combine(dalDir, "DAL" + tablename + ".cs");
Directory.CreateDirectory(dalDir);
File.WriteAllText(dalFile, sb.ToString());
}
public static void GenerateBLL(DataTable dtCols, DataRow drCols, string tablename, GeneratorArgs args)
{
string pknetTypeName = string.Empty;
if (drCols != null)
{
string pkdataType = Convert.ToString(drCols["Data_Type"]);
Type pknetType = GetTypeByDBType(pkdataType);
//處理可空數據類型
if (pknetType.IsValueType)
{
pknetTypeName = pknetType.ToString() + "?";
}
else
{
pknetTypeName = pknetType.ToString();
}
pknetTypeName = pknetTypeName.Replace("System.", string.Empty);
}
StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using System.Data;");
sb.AppendLine("using System.Data.SqlClient;");
sb.AppendLine("using System.Text;");
sb.AppendLine("using " + args.RootNamespace + ".Model;");
sb.AppendLine("using " + args.RootNamespace + ".DAL;");
sb.AppendLine("");
sb.AppendLine("namespace " + args.RootNamespace + ".BLL");
sb.AppendLine("{");
sb.AppendLine("partial class " + tablename + "BLL{");
sb.AppendLine("public void Insert(" + tablename + " model){");
sb.AppendLine(" new " + tablename + "DAL().Insert(model);}");
sb.AppendLine("public void Update(" + tablename + " model){");
sb.AppendLine(" new " + tablename + "DAL().Update(model);}");
if (drCols != null)
{
sb.AppendLine("public " + tablename + " Get(" + pknetTypeName + " " + drCols["Column_Name"].ToString() + "){");
sb.AppendLine("return new " + tablename + "DAL().Get(" + drCols["Column_Name"].ToString() + ");}");
sb.AppendLine("public bool RepeatChk(string wherestr, List<SqlParameter> whereParameters, " + pknetTypeName + " " + drCols["Column_Name"].ToString() + "){");
sb.AppendLine("return new " + tablename + "DAL().RepeatChk(wherestr,whereParameters," + drCols["Column_Name"].ToString() + ");}");
}
sb.AppendLine("public ResultPageingObject SelectByPage(int pageIndex, int pageSize, string wherestr, string orderby, List<SqlParameter> whereParameters){");
sb.AppendLine("return new " + tablename + "DAL().SelectByPage(pageIndex,pageSize,wherestr,orderby,whereParameters);}");
sb.AppendLine("public DataTable SelectList(string wherestr, string orderby, List<SqlParameter> whereParameters){");
sb.AppendLine("return new " + tablename + "DAL().SelectList(wherestr,orderby,whereParameters);}");
sb.AppendLine("public List<" + tablename+ "> SelectLists(string wherestr, string orderby, List<SqlParameter> whereParameters){");
sb.AppendLine("return new " + tablename + "DAL().SelectLists(wherestr,orderby,whereParameters);}");
sb.AppendLine("}}");
string bllDir = Path.Combine(args.OutputDir, "BLL");
string bllFile =
Path.Combine(bllDir, "BLL" + tablename + ".cs");
Directory.CreateDirectory(bllDir);
File.WriteAllText(bllFile, sb.ToString());
}
}
}