分享
 
 
 

自动生成数据对象代码和CRUD操作的C#代码生成器

王朝c#·作者佚名  2006-12-20
窄屏简体版  字體: |||超大  

笔者近期在Vs2005平台和SqlServer2005平台之上研发了一个C#代码生成器,支持数据库表和C#数据对象的直接映射,以及CRUD操作代码的自动生成,用户只需要实现IDAL接口即可,该工具能够显著提高开发速度,让开发人员从繁重的数据库表对象封装编码中解脱出来(工具下载地址:http://itabby.com/index-5.asp),现特将核心处理代码进行发表,仅供参考:

///数据对象提取部分数据库类型和C#对象类型之间的转换过程

private string ConvertSqlDataReader(string sqlReader,string type, int i)

{

switch (type.Trim().ToLower())

{

case "bigint": return sqlReader + ".GetInt64(" + i.ToString() + ")";

///case "binary": return sqlReader + ".GetValue(" + i.ToString() + ")";

case "bit": return sqlReader + ".GetBoolean(" + i.ToString() + ")";

case "char": return sqlReader + ".GetString(" + i.ToString() + ")";

case "datetime": return sqlReader + ".GetDateTime(" + i.ToString() + ")";

case "decimal": return sqlReader + ".GetDecimal(" + i.ToString() + ")";

case "float": return sqlReader + ".GetFloat(" + i.ToString() + ")";

///case "image": return sqlReader + ".GetValue(" + i.ToString() + ")";

case "int": return sqlReader + ".GetInt32(" + i.ToString() + ")";

case "money": return sqlReader + ".GetDecimal(" + i.ToString() + ")";

case "nchar": return sqlReader + ".GetString(" + i.ToString() + ")";

case "ntext": return sqlReader + ".GetString(" + i.ToString() + ")";

case "nvarchar": return sqlReader + ".GetString(" + i.ToString() + ")";

case "real": return sqlReader + ".GetFloat(" + i.ToString() + ")";

case "smalldatetime": return sqlReader + ".GetDateTime(" + i.ToString() + ")";

case "smallint": return sqlReader + ".GetInt16(" + i.ToString() + ")";

case "smallmoney": return sqlReader + ".GetDecimal(" + i.ToString() + ")";

case "text": return sqlReader + ".GetString(" + i.ToString() + ")";

case "timestamp": return sqlReader + ".GetDateTime(" + i.ToString() + ")";

case "tinyint": return sqlReader + ".GetByte(" + i.ToString() + ")";

case "udt": return sqlReader + ".GetValue(" + i.ToString() + ")";

case "uniqueidentifier": return sqlReader + ".GetGuid(" + i.ToString() + ")";

///case "varbinary": return sqlReader + ".GetValue(" + i.ToString() + ")";

case "varchar": return sqlReader + ".GetString(" + i.ToString() + ")";

case "variant": return sqlReader + ".GetValue(" + i.ToString() + ")";

case "xml": return sqlReader + ".GetString(" + i.ToString() + ")";

case "numeric": return sqlReader + ".GetDecimal(" + i.ToString() + ")";

default: throw new ArgumentException(type + " not in Itabby.Product.SqlCode.SqlCode.ConvertGetMethod process list.");

}

}

///数据库类型完全限定名称还原

private string ConvertSqlDbType(string type)

{

switch (type.Trim().ToLower())

{

case "bigint": return "System.Data.SqlDbType.BigInt";

case "binary": return "System.Data.SqlDbType.Binary";

case "bit": return "System.Data.SqlDbType.Bit";

case "char": return "System.Data.SqlDbType.Char";

case "datetime": return "System.Data.SqlDbType.DateTime";

case "decimal": return "System.Data.SqlDbType.Decimal";

case "float": return "System.Data.SqlDbType.Float";

case "image": return "System.Data.SqlDbType.Image";

case "int": return "System.Data.SqlDbType.Int";

case "money": return "System.Data.SqlDbType.Money";

case "nchar": return "System.Data.SqlDbType.NChar";

case "ntext": return "System.Data.SqlDbType.NText";

case "nvarchar": return "System.Data.SqlDbType.NVarChar";

case "real": return "System.Data.SqlDbType.Real";

case "smalldatetime": return "System.Data.SqlDbType.SmallDateTime";

case "smallint": return "System.Data.SqlDbType.SmallInt";

case "smallmoney": return "System.Data.SqlDbType.SmallMoney";

case "text": return "System.Data.SqlDbType.Text";

case "timestamp": return "System.Data.SqlDbType.Timestamp";

case "tinyint": return "System.Data.SqlDbType.TinyInt";

case "udt": return "System.Data.SqlDbType.Udt";

case "uniqueidentifier": return "System.Data.SqlDbType.UniqueIdentifier";

case "varbinary": return "System.Data.SqlDbType.VarBinary";

case "varchar": return "System.Data.SqlDbType.VarChar";

case "variant": return "System.Data.SqlDbType.Variant";

case "xml": return "System.Data.SqlDbType.Xml";

case "numeric": return "System.Data.SqlDbType.Decimal";

default: throw new ArgumentException(type + " not in Itabby.Product.SqlCode.SqlCode.ConvertSqlDbType process list.");

}

}

///加载数据库表对象

public ArrayList LoadTables(string sConnectionString)

{

using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConvertConnectionString(sConnectionString)))

{

_sTables.Clear();

conn.Open();

System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();

cmd.CommandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' Order by TABLE_NAME";

System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();

while (dr.Read())

{

_sTables.Add(dr.GetString(0));

}

dr.Close();

conn.Close();

}

return _sTables;

}

///加载数据库列对象

public ArrayList LoadColumns(string sConnectionString,string sTable)

{

using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConvertConnectionString(sConnectionString)))

{

_sColumns.Clear();

conn.Open();

System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();

///get pk in current table

cmd.CommandText = "SELECT Column_Name FROM INFORMATION_SCHEMA .KEY_COLUMN_USAGE where Table_Name = '" + sTable + "' and constraint_name in(select name from sys.objects where parent_object_id = ( select OBJECT_ID('" + sTable + "')) and type = 'pk')";

System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();

ArrayList pks = new ArrayList();

while (dr.Read())

{

pks.Add(dr.GetString(0));

}

dr.Close();

///get columns in current table

cmd.CommandText = "SELECT COLUMN_NAME,Data_Type,Character_maximum_length,numeric_precision,numeric_scale,COLUMNPROPERTY( OBJECT_ID('" + sTable + "'),COLUMN_NAME,'IsIdentity') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + sTable + "' Order by COLUMN_NAME";

dr = cmd.ExecuteReader();

bool pk = false;

while (dr.Read())

{

///pk

foreach (string s in pks)

{

if (s.Equals(dr.GetString(0)))

{

pk = true;

}

}

_sColumns.Add(dr.GetString(0) + ";" + dr.GetString(1) + ";" + Convert.ToString(dr.IsDBNull(2) ? string.Empty : dr.GetValue(2).ToString()) + ";" + Convert.ToString(dr.IsDBNull(3) ? string.Empty : dr.GetValue(3).ToString()) + ";" + Convert.ToString(dr.IsDBNull(4) ? string.Empty : dr.GetValue(4).ToString()) + ";" + pk.ToString() + ";" + dr.GetValue(5).Equals(1).ToString());

pk = false;

}

dr.Close();

conn.Close();

}

return _sColumns;

}

///加载一个数据对象

public string GetObjectCode(string sConnectionString, string sTable, ArrayList columns, bool[] operations)

{

System.Text.StringBuilder sObjectCode = new StringBuilder();

sObjectCode.Append(USING_DECLARE + "\r\n" + NAMESPACE_DECLARE + "\r\n" + NAMESPACE_BEGIN + "\r\n");

sObjectCode.Append("\t" + CLASS_DECLARE + sTable + "\r\n\t" + CLASS_BODY_BEGIN + "\r\n");

using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConvertConnectionString(sConnectionString)))

{

System.Data.SqlClient.SqlDataAdapter adpt = new System.Data.SqlClient.SqlDataAdapter("select top 1 * from " + sTable,conn);

DataTable cols = new DataTable();

adpt.Fill(cols);

sObjectCode.Append("\t\t" + REGION_BEGIN + "Attribute Block" + "\r\n");

if (operations[0])

{

foreach (System.Data.DataColumn column in cols.Columns)

{

///private var;

sObjectCode.Append("\t\t" + column.DataType.FullName + " _" + column.ColumnName + ";" + "\r\n");

///attribute

sObjectCode.Append("\t\tpublic " + column.DataType.FullName + " " + column.ColumnName.ToUpper() + ATTRIBUTE_BEGIN);

///get

sObjectCode.Append(GET_ATTRIBUTE_BEGIN + " return " + " _" + column.ColumnName + ";");

sObjectCode.Append(GET_ATTRIBUTE_END);

///set

sObjectCode.Append(SET_ATTRIBUTE_BEGIN + " _" + column.ColumnName + " = value;");

sObjectCode.Append(SET_ATTRIBUTE_END);

sObjectCode.Append(ATTRIBUTE_END + "\r\n");

}

}

sObjectCode.Append("\t\t" + REGION_END);

sObjectCode.Append("\r\n\t\t" + REGION_BEGIN + "Method Blok");

///Add operation

if (operations[1]) sObjectCode.Append(GetAddCode("DataObject_" + sTable, columns));

///Update operation

if (operations[2]) sObjectCode.Append(GetUpdateCode("DataObject_" + sTable, columns));

///Delete operation

if (operations[3]) sObjectCode.Append(GetDeleteCode("DataObject_" + sTable, columns));

///Select operation

if (operations[4]) sObjectCode.Append(GetGetCode("DataObject_" + sTable, columns));

///List operation

if (operations[5]) sObjectCode.Append(GetListCode("DataObject_" + sTable, columns));

sObjectCode.Append("\r\n\t\t" + REGION_END);

}

sObjectCode.Append("\r\n\t" + CLASS_BODY_END);

sObjectCode.Append("\r\n" + NAMESPACE_END);

return sObjectCode.ToString();

}

///生成Add方法代码

private string GetAddCode(string sObject,ArrayList columns)

{

System.Text.StringBuilder sObjectCode = new StringBuilder();

sObjectCode.Append("\r\n\t\tpublic static int Add(" + sObject + " obj,IDAL idal,SqlTransaction trans)");

sObjectCode.Append("\r\n\t\t{");

sObjectCode.Append("\r\n\t\t\tconst string sSql = \"insert into " + sObject.Substring(11));

sObjectCode.Append("(");

int iKey = 0;

foreach (string s in columns)

{

///All columns without identity columns

if (s.Split(';')[6].ToLower().Equals("true")) continue;

sObjectCode.Append(" " + s.Split(';')[0] + ",");

iKey += 1;

}

sObjectCode.Remove(sObjectCode.Length - 1, 1);

sObjectCode.Append(")");

sObjectCode.Append(" values ");

sObjectCode.Append("(");

foreach (string s in columns)

{

///All columns without identity columns

if (s.Split(';')[6].ToLower().Equals("true")) continue;

sObjectCode.Append(" @" + s.Split(';')[0] + ",");

}

sObjectCode.Remove(sObjectCode.Length - 1, 1);

sObjectCode.Append(")");

sObjectCode.Append(";\";\r\n");

sObjectCode.Append("\t\t\t" + REGION_BEGIN + "Parameters Block" + "\r\n");

sObjectCode.Append("\t\t\tSqlParameter[] parameters = new SqlParameter[" + iKey + "];\r\n");

iKey = 0;

for (int i = 0; i < columns.Count; i++)

{

///All columns without identity columns

if (columns[i].ToString().Split(';')[6].ToLower().Equals("true")) continue;

sObjectCode.Append("\t\t\tparameters[" + iKey + "] = new SqlParameter();\r\n");

sObjectCode.Append("\t\t\tparameters[" + iKey + "].ParameterName = \"@" + columns[i].ToString().Split(';')[0] + "\";\r\n");

if (columns[i].ToString().Split(';')[2].Equals(string.Empty))

{

if (!columns[i].ToString().Split(';')[3].Equals(string.Empty))

{

sObjectCode.Append("\t\t\tparameters[" + iKey + "].Size = " + columns[i].ToString().Split(';')[3] + ";\r\n");

}

}

else

{

sObjectCode.Append("\t\t\tparameters[" + iKey + "].Size = " + columns[i].ToString().Split(';')[2] + ";\r\n");

}

sObjectCode.Append("\t\t\tparameters[" + iKey + "].SqlDbType = " + ConvertSqlDbType(columns[i].ToString().Split(';')[1]) + ";\r\n");

sObjectCode.Append("\t\t\tparameters[" + iKey + "].Value = obj." + columns[i].ToString().Split(';')[0].ToUpper() + ";\r\n");

iKey += 1;

}

sObjectCode.Append("\t\t\t" + REGION_END + "\r\n");

sObjectCode.Append("\t\t\treturn idal.ExecuteNonQuery(sSql,parameters,trans);");

sObjectCode.Append("\r\n\t\t}");

return sObjectCode.ToString();

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有