主要跟大家交流下T4,我这里针对的是mysql,我本人比较喜欢用mysql,所以语法针对mysql,所以你要准备mysql的DLL了,同理sqlserver差不多,有兴趣可以自己写写,首先网上找了一个T4的帮助类,得到一些数据库属性,命名为 DbHelper.ttinclude

  1. <#@ template debug="false" hostspecific="false" language="C#" #>
  2. <#@ assembly name="System.Core.dll" #>
  3. <#@ assembly name="System.Data.dll" #>
  4. <#@ assembly name="System.Data.DataSetExtensions.dll" #>
  5. <#@ assembly name="System.Xml.dll" #>
  6. <#@ assembly name="MySql.Data" #>
  7. <#@ import namespace="System" #>
  8. <#@ import namespace="System.Xml" #>
  9. <#@ import namespace="System.Linq" #>
  10. <#@ import namespace="System.Text" #>
  11. <#@ import namespace="System.Data" #>
  12. <#@ import namespace=" System.Data.SqlClient" #>
  13. <#@ import namespace="MySql.Data.MySqlClient" #>
  14. <#@ import namespace="System.Collections.Generic" #>
  15. <#@ import namespace="System.IO" #>
  16. <#@ import namespace="System.Text.RegularExpressions" #><#+
  17.  
  18. #region GetDbTables
  19. public class DbHelper
  20. {
  21.  
  22. #region 去下划线,转大写
  23. public static string ToSplitFirstUpper(string file)
  24. {
  25. string[] words = file.Split('_');
  26. StringBuilder firstUpperWorld = new StringBuilder();
  27. foreach (string word in words)
  28. {
  29. string firstUpper = ToFirstUpper(word);
  30. firstUpperWorld.Append(firstUpper);
  31. }
  32. string firstUpperFile = firstUpperWorld.ToString().TrimEnd(new char[] { '_' });
  33. return firstUpperFile;
  34. }
  35.  
  36. // 将字符串设置成首字母大写
  37. public static string ToFirstUpper(string field)
  38. {
  39. string first = field.Substring(, ).ToUpperInvariant();
  40. string result = first;
  41. if (field.Length > )
  42. {
  43. string after = field.Substring();
  44. result = first + after;
  45. }
  46. return result;
  47. }
  48.  
  49. #endregion
  50.  
  51. #region 生成简单的sql语句
  52. public static string GetInsertSql(string connectionString, string database, string tableName)
  53. {
  54. var list = GetDbColumns(connectionString, database, tableName);
  55. StringBuilder sb1 = new StringBuilder();
  56. StringBuilder sb2 = new StringBuilder();
  57. foreach (var item in list)
  58. {
  59. string field = item.Field;
  60. if (field.ToLower() == "id") continue;
  61. sb1.Append(field).Append(", ");
  62. sb2.Append("?").Append(field).Append(", ");
  63. }
  64. string s1 = sb1.ToString().Trim(new char[] { ',', ' ' });
  65. string s2 = sb2.ToString().Trim(new char[] { ',', ' ' });
  66. return string.Format("INSERT INTO {0}({1}) VALUES({2})", tableName, s1, s2);
  67.  
  68. }
  69.  
  70. public static string GetParameter(string connectionString, string database, string tableName, bool hasId)
  71. {
  72. var list = GetDbColumns(connectionString, database, tableName);
  73. StringBuilder sb = new StringBuilder();
  74. sb.Append("MySqlParameter[] paras = new MySqlParameter[] { \r\n");
  75. foreach (var item in list)
  76. {
  77. if (item.Field.ToLower() == "id" && !hasId) continue;
  78. sb.AppendFormat(" new MySqlParameter(\"{0}\", this.{1}),\r\n", item.Field, ToSplitFirstUpper(item.Field));
  79. }
  80. string s = sb.ToString().Trim(new char[] { ',', ' ', '\r', '\n' });
  81. s = s + "\r\n };\r\n";
  82. return s;
  83. }
  84.  
  85. public static string GetUpdateSql(string connectionString, string database, string tableName)
  86. {
  87. var list = GetDbColumns(connectionString, database, tableName);
  88. StringBuilder sb1 = new StringBuilder();
  89. foreach (var item in list)
  90. {
  91. string field = item.Field;
  92. if (field.ToLower() == "id") continue;
  93. sb1.Append(field).Append(" = ").Append("?").Append(field).Append(", ");
  94.  
  95. }
  96. string s1 = sb1.ToString().Trim(new char[] { ',', ' ' });
  97. return string.Format("UPDATE {0} SET {1} WHERE id = ?id", tableName, s1);
  98.  
  99. }
  100.  
  101. #endregion
  102.  
  103. #region GetDbTables
  104.  
  105. public static List<DbTable> GetDbTables(string connectionString, string database)
  106. {
  107.  
  108. #region SQL
  109. string sql = string.Format("SHOW TABLE STATUS FROM {0};", database);
  110. #endregion
  111. DataTable dt = GetDataTable(connectionString, sql);
  112. return dt.Rows.Cast<DataRow>().Select(row => new DbTable
  113. {
  114. TableName = row.Field<string>("Name"),
  115. Rows = row.Field<UInt64>("Rows"),
  116. Comment = row.Field<string>("Comment")
  117. }).ToList();
  118. }
  119. #endregion
  120.  
  121. #region GetDbColumns
  122.  
  123. public static List<DbColumn> GetDbColumns(string connectionString, string database, string tableName)
  124. {
  125. #region SQL
  126. string sql = string.Format("SHOW FULL COLUMNS FROM {0} FROM {1};", tableName, database);
  127. #endregion
  128. DataTable dt = GetDataTable(connectionString, sql);
  129. return dt.Rows.Cast<DataRow>().Select(row => new DbColumn
  130. {
  131. IsPrimaryKey = !String.IsNullOrEmpty(row.Field<string>("Key")),
  132. Field = row.Field<string>("Field"),
  133. Type = row.Field<string>("Type"),
  134. Comment = row.Field<string>("Comment"),
  135. IsNullable = row.Field<string>("NULL") == "YES"
  136. }).ToList();
  137. }
  138.  
  139. #endregion
  140.  
  141. #region GetDataTable
  142.  
  143. public static DataTable GetDataTable(string connectionString, string commandText, params SqlParameter[] parms)
  144. {
  145. using (MySqlConnection connection = new MySqlConnection(connectionString))
  146. {
  147. MySqlCommand command = connection.CreateCommand();
  148. command.CommandText = commandText;
  149. command.Parameters.AddRange(parms);
  150. MySqlDataAdapter adapter = new MySqlDataAdapter(command);
  151.  
  152. DataTable dt = new DataTable();
  153. adapter.Fill(dt);
  154.  
  155. return dt;
  156. }
  157. }
  158.  
  159. #endregion
  160. }
  161. #endregion
  162.  
  163. #region DbTable
  164. /// <summary>
  165. /// 表结构
  166. /// </summary>
  167. public sealed class DbTable
  168. {
  169. /// <summary>
  170. /// 表名称
  171. /// </summary>
  172. public string TableName { get; set; }
  173.  
  174. /// <summary>
  175. /// 行数
  176. /// </summary>
  177. public UInt64 Rows { get; set; }
  178.  
  179. /// <summary>
  180. /// 描述信息
  181. /// </summary>
  182. public string Comment { get; set; }
  183. }
  184. #endregion
  185.  
  186. #region DbColumn
  187. /// <summary>
  188. /// 表字段结构
  189. /// </summary>
  190. public sealed class DbColumn
  191. {
  192. /// <summary>
  193. /// 是否主键
  194. /// </summary>
  195. public bool IsPrimaryKey { get; set; }
  196. /// <summary>
  197. /// 字段名称
  198. /// </summary>
  199. public string Field { get; set; }
  200. /// <summary>
  201. /// 字段类型 int(11)
  202. /// </summary>
  203. public string Type { get; set; }
  204. /// <summary>
  205. /// 字段类型int
  206. /// </summary>
  207. public string ColumnType
  208. {
  209. get
  210. {
  211. return Type.IndexOf('(') == - ? Type : Type.Substring(, Type.IndexOf('('));
  212. }
  213. }
  214. /// <summary>
  215. /// 数据库类型对应的C#类型
  216. /// </summary>
  217. public string CSharpType
  218. {
  219. get
  220. {
  221. return MysqlDbTypeMap.MapCsharpType(ColumnType);
  222. }
  223. }
  224. /// <summary>
  225. ///
  226. /// </summary>
  227. public Type CommonType
  228. {
  229. get
  230. {
  231. return MysqlDbTypeMap.MapCommonType(ColumnType);
  232. }
  233. }
  234. /// <summary>
  235. /// 描述
  236. /// </summary>
  237. public string Comment { get; set; }
  238. /// <summary>
  239. /// 是否允许空
  240. /// </summary>
  241. public bool IsNullable { get; set; }
  242.  
  243. /// <summary>
  244. /// 字符长度
  245. /// </summary>
  246. public int CharLength
  247. {
  248. get
  249. {
  250. Regex regex = new Regex(@"(?<=\()\d*?(?=\))", RegexOptions.Singleline);
  251. if (regex.IsMatch(Type))
  252. {
  253. Match match = regex.Match(Type);
  254. while (match != null && match.Success)
  255. {
  256. int charLength;
  257. if (Int32.TryParse(match.Value, out charLength))
  258. {
  259. return charLength;
  260. }
  261. }
  262. }
  263. return ;
  264. }
  265. }
  266. }
  267. #endregion
  268.  
  269. #region SqlServerDbTypeMap
  270.  
  271. public class MysqlDbTypeMap
  272. {
  273. public static string MapCsharpType(string dbtype)
  274. {
  275. if (string.IsNullOrEmpty(dbtype)) return dbtype;
  276. dbtype = dbtype.ToLower();
  277. string csharpType = "object";
  278. switch (dbtype)
  279. {
  280. case "bigint": csharpType = "long"; break;
  281. case "binary": csharpType = "byte[]"; break;
  282. case "bit": csharpType = "bool"; break;
  283. case "char": csharpType = "string"; break;
  284. case "date": csharpType = "DateTime"; break;
  285. case "datetime": csharpType = "DateTime"; break;
  286. case "datetime2": csharpType = "DateTime"; break;
  287. case "datetimeoffset": csharpType = "DateTimeOffset"; break;
  288. case "dityint": csharpType = "bool"; break;
  289. case "decimal": csharpType = "decimal"; break;
  290. case "float": csharpType = "double"; break;
  291. case "image": csharpType = "byte[]"; break;
  292. case "int": csharpType = "int"; break;
  293. case "money": csharpType = "decimal"; break;
  294. case "nchar": csharpType = "string"; break;
  295. case "ntext": csharpType = "string"; break;
  296. case "numeric": csharpType = "decimal"; break;
  297. case "nvarchar": csharpType = "string"; break;
  298. case "real": csharpType = "Single"; break;
  299. case "smalldatetime": csharpType = "DateTime"; break;
  300. case "smallint": csharpType = "short"; break;
  301. case "smallmoney": csharpType = "decimal"; break;
  302. case "sql_variant": csharpType = "object"; break;
  303. case "sysname": csharpType = "object"; break;
  304. case "text": csharpType = "string"; break;
  305. case "longtext": csharpType = "string"; break;
  306. case "time": csharpType = "TimeSpan"; break;
  307. case "timestamp": csharpType = "byte[]"; break;
  308. case "tinyint": csharpType = "byte"; break;
  309. case "uniqueidentifier": csharpType = "Guid"; break;
  310. case "varbinary": csharpType = "byte[]"; break;
  311. case "varchar": csharpType = "string"; break;
  312. case "xml": csharpType = "string"; break;
  313. default: csharpType = "object"; break;
  314. }
  315. return csharpType;
  316. }
  317.  
  318. public static Type MapCommonType(string dbtype)
  319. {
  320. if (string.IsNullOrEmpty(dbtype)) return Type.Missing.GetType();
  321. dbtype = dbtype.ToLower();
  322. Type commonType = typeof(object);
  323. switch (dbtype)
  324. {
  325. case "bigint": commonType = typeof(long); break;
  326. case "binary": commonType = typeof(byte[]); break;
  327. case "bit": commonType = typeof(bool); break;
  328. case "char": commonType = typeof(string); break;
  329. case "date": commonType = typeof(DateTime); break;
  330. case "datetime": commonType = typeof(DateTime); break;
  331. case "datetime2": commonType = typeof(DateTime); break;
  332. case "datetimeoffset": commonType = typeof(DateTimeOffset); break;
  333. case "dityint": commonType = typeof(Boolean); break;
  334. case "decimal": commonType = typeof(decimal); break;
  335. case "float": commonType = typeof(double); break;
  336. case "image": commonType = typeof(byte[]); break;
  337. case "int": commonType = typeof(int); break;
  338. case "money": commonType = typeof(decimal); break;
  339. case "nchar": commonType = typeof(string); break;
  340. case "ntext": commonType = typeof(string); break;
  341. case "numeric": commonType = typeof(decimal); break;
  342. case "nvarchar": commonType = typeof(string); break;
  343. case "real": commonType = typeof(Single); break;
  344. case "smalldatetime": commonType = typeof(DateTime); break;
  345. case "smallint": commonType = typeof(short); break;
  346. case "smallmoney": commonType = typeof(decimal); break;
  347. case "sql_variant": commonType = typeof(object); break;
  348. case "sysname": commonType = typeof(object); break;
  349. case "text": commonType = typeof(string); break;
  350. case "time": commonType = typeof(TimeSpan); break;
  351. case "timestamp": commonType = typeof(byte[]); break;
  352. case "tinyint": commonType = typeof(byte); break;
  353. case "uniqueidentifier": commonType = typeof(Guid); break;
  354. case "varbinary": commonType = typeof(byte[]); break;
  355. case "varchar": commonType = typeof(string); break;
  356. case "xml": commonType = typeof(string); break;
  357. default: commonType = typeof(object); break;
  358. }
  359. return commonType;
  360. }
  361. }
  362. #endregion
  363.  
  364. #>

在加一个c#的sql帮助类, 命名为DBHelper.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Security.Cryptography;
  8. using System.Configuration;
  9. using MySql.Data.MySqlClient;
  10. using System.Reflection;
  11. using System.Text;
  12.  
  13. namespace ToolSite.Entity
  14. {
  15.  
  16. public class DBHelper
  17. {
  18. //添加到配置文件的<configuration>节点中
  19. // <connectionStrings>
  20. // <!--改写数据库名,登陆名,密码-->
  21. // <add name="conStr" connectionString="Data Source=.;Initial Catalog=;User ID=;Password="/>
  22. //
  23. // </connectionStrings>
  24. //<appSettings>
  25. // <add key="dbConnection" value="server=192.168.1.111\SQL2005;database=GCUMS;UID=sa;PWD=sa;max pool size=20000;Pooling=true;"/>
  26. // </appSettings>
  27. //先添加configuration引用,引入命名空间
  28. //private static readonly string conStr = ConfigurationManager.AppSettings["connstr"];
  29. //private static readonly string conStr = Config.ConnStr;
  30. /// <summary>
  31. /// 获得连接字符串
  32. /// </summary>
  33. /// <returns></returns>
  34. public static MySqlConnection getConn()
  35. {
  36. return new MySqlConnection(Config.ConnStr);
  37. }
  38. /// <summary>
  39. /// 查询获得首行首列的值,格式化SQL语句
  40. /// </summary>
  41. /// <param name="sql"></param>
  42. /// <returns></returns>
  43. public static object Scalar(String sql)
  44. {
  45. using (MySqlConnection con = getConn())
  46. {
  47. try
  48. {
  49. MySqlCommand com = new MySqlCommand(sql, con);
  50. con.Open();
  51. return com.ExecuteScalar();
  52. }
  53. catch (Exception ex)
  54. {
  55. throw ex;
  56. }
  57. }
  58. }
  59. /// <summary>
  60. /// 查询获得首行首列的值 参数化sql语句
  61. /// </summary>
  62. /// <param name="paras">参数数组</param>
  63. /// <param name="sql">sql语句</param>
  64. /// <returns></returns>
  65. public static object Scalar(string sql, MySqlParameter[] paras)
  66. {
  67. using (MySqlConnection con = getConn())
  68. {
  69. try
  70. {
  71. MySqlCommand com = new MySqlCommand(sql, con);
  72. con.Open();
  73. if (paras != null) //如果参数
  74. {
  75. com.Parameters.AddRange(paras);
  76. }
  77. return com.ExecuteScalar();
  78. }
  79. catch (Exception ex)
  80. {
  81. throw ex;
  82.  
  83. }
  84. }
  85. }
  86.  
  87. /// <summary>
  88. /// 增删改操作,返回受影响的行数,格式化SQL语句
  89. /// </summary>
  90. /// <param name="sql"></param>
  91. /// <returns></returns>
  92. public static int NoneQuery(String sql)
  93. {
  94.  
  95. using (MySqlConnection conn = getConn())
  96. {
  97. conn.Open();
  98. using (MySqlCommand comm = new MySqlCommand(sql, conn))
  99. {
  100. return comm.ExecuteNonQuery();
  101. }
  102.  
  103. }
  104. }
  105. /// <summary>
  106. /// 增删改操作,返回受影响的行数 存储过程
  107. /// </summary>
  108. /// <param name="sql">存储过程名称</param>
  109. /// <param name="paras">参数</param>
  110. /// <returns></returns>
  111. public static int NoneQuery(String sql, MySqlParameter[] paras)
  112. {
  113. using (MySqlConnection conn = getConn())
  114. {
  115. conn.Open();
  116. using (MySqlCommand comm = new MySqlCommand(sql, conn))
  117. {
  118. comm.Parameters.AddRange(paras);
  119. return comm.ExecuteNonQuery();
  120. }
  121.  
  122. }
  123. }
  124. /// <summary>
  125. /// 查询操作,返回一个数据表
  126. /// </summary>
  127. /// <param name="sql"></param>
  128. /// <returns></returns>
  129. public static DataTable GetDateTable(String sql)
  130. {
  131. using (MySqlConnection con = getConn())
  132. {
  133. DataTable dt = new DataTable();
  134. try
  135. {
  136. MySqlDataAdapter sda = new MySqlDataAdapter(sql, con);
  137. sda.Fill(dt);
  138. }
  139. catch (Exception ex)
  140. {
  141. throw ex;
  142. }
  143. return dt;
  144. }
  145. }
  146. /// <summary>
  147. /// 查询操作,返回一个数据表,存储过程
  148. /// </summary>
  149. /// <param name="sp_Name">存储过程名称</param>
  150. /// <param name="paras">存储过程参数</param>
  151. /// <returns></returns>
  152. public static DataTable GetDateTable(String sql, MySqlParameter[] paras)
  153. {
  154. using (MySqlConnection con = getConn())
  155. {
  156. DataTable dt = new DataTable();
  157. try
  158. {
  159. MySqlCommand com = new MySqlCommand(sql, con);
  160. com.Parameters.AddRange(paras);
  161. MySqlDataAdapter sda = new MySqlDataAdapter(com);
  162. sda.Fill(dt);
  163. }
  164. catch (Exception ex)
  165. {
  166. throw ex;
  167. }
  168. return dt;
  169. }
  170. }
  171.  
  172. }
  173.  
  174. /// <summary>
  175. /// DataTable与实体类互相转换
  176. /// </summary>
  177. /// <typeparam name="T">实体类</typeparam>
  178. public class DatatableFill<T> where T : new()
  179. {
  180. #region DataTable转换成实体类
  181. /// <summary>
  182. /// 填充对象列表:用DataSet的第一个表填充实体类
  183. /// </summary>
  184. /// <param name="ds">DataSet</param>
  185. /// <returns></returns>
  186. public List<T> FillModel(DataSet ds)
  187. {
  188. if (ds == null || ds.Tables[] == null || ds.Tables[].Rows.Count == )
  189. {
  190. return new List<T>();
  191. }
  192. else
  193. {
  194. return FillModel(ds.Tables[]);
  195. }
  196. }
  197.  
  198. /// <summary>
  199. /// 填充对象列表:用DataSet的第index个表填充实体类
  200. /// </summary>
  201. public List<T> FillModel(DataSet ds, int index)
  202. {
  203. if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == )
  204. {
  205. return new List<T>() ;
  206. }
  207. else
  208. {
  209. return FillModel(ds.Tables[index]);
  210. }
  211. }
  212.  
  213. /// <summary>
  214. /// 填充对象列表:用DataTable填充实体类
  215. /// </summary>
  216. public List<T> FillModel(DataTable dt)
  217. {
  218. if (dt == null || dt.Rows.Count == )
  219. {
  220. return new List<T>();
  221. }
  222. List<T> modelList = new List<T>();
  223. foreach (DataRow dr in dt.Rows)
  224. {
  225. //T model = (T)Activator.CreateInstance(typeof(T));
  226. T model = new T();
  227. for (int i = ; i < dr.Table.Columns.Count; i++)
  228. {
  229. PropertyInfo propertyInfo = model.GetType().GetProperty(ToSplitFirstUpper(dr.Table.Columns[i].ColumnName));
  230. if (propertyInfo != null && dr[i] != DBNull.Value)
  231. propertyInfo.SetValue(model, dr[i], null);
  232. }
  233.  
  234. modelList.Add(model);
  235. }
  236. return modelList;
  237. }
  238.  
  239. /// <summary>
  240. /// 填充对象:用DataRow填充实体类
  241. /// </summary>
  242. public T FillModel(DataRow dr)
  243. {
  244. if (dr == null)
  245. {
  246. return default(T);
  247. }
  248.  
  249. //T model = (T)Activator.CreateInstance(typeof(T));
  250. T model = new T();
  251.  
  252. for (int i = ; i < dr.Table.Columns.Count; i++)
  253. {
  254. PropertyInfo propertyInfo = model.GetType().GetProperty(ToSplitFirstUpper(dr.Table.Columns[i].ColumnName));
  255. if (propertyInfo != null && dr[i] != DBNull.Value)
  256. propertyInfo.SetValue(model, dr[i], null);
  257. }
  258. return model;
  259. }
  260.  
  261. // 去下划线,转大写
  262. public static string ToSplitFirstUpper(string file)
  263. {
  264. string[] words = file.Split('_');
  265. StringBuilder firstUpperWorld = new StringBuilder();
  266. foreach (string word in words)
  267. {
  268. string firstUpper = ToFirstUpper(word);
  269. firstUpperWorld.Append(firstUpper);
  270. }
  271. string firstUpperFile = firstUpperWorld.ToString().TrimEnd(new char[] { '_' });
  272. return firstUpperFile;
  273. }
  274.  
  275. // 将字符串设置成首字母大写
  276. public static string ToFirstUpper(string field)
  277. {
  278. string first = field.Substring(, ).ToUpperInvariant();
  279. string result = first;
  280. if (field.Length > )
  281. {
  282. string after = field.Substring();
  283. result = first + after;
  284. }
  285. return result;
  286. }
  287. #endregion
  288.  
  289. #region 实体类转换成DataTable
  290.  
  291. /// <summary>
  292. /// 实体类转换成DataSet
  293. /// </summary>
  294. /// <param name="modelList">实体类列表</param>
  295. /// <returns></returns>
  296. public DataSet FillDataSet(List<T> modelList)
  297. {
  298. if (modelList == null || modelList.Count == )
  299. {
  300. return null;
  301. }
  302. else
  303. {
  304. DataSet ds = new DataSet();
  305. ds.Tables.Add(FillDataTable(modelList));
  306. return ds;
  307. }
  308. }
  309.  
  310. /// <summary>
  311. /// 实体类转换成DataTable
  312. /// </summary>
  313. /// <param name="modelList">实体类列表</param>
  314. /// <returns></returns>
  315. public DataTable FillDataTable(List<T> modelList)
  316. {
  317. if (modelList == null || modelList.Count == )
  318. {
  319. return null;
  320. }
  321. DataTable dt = CreateData(modelList[]);
  322.  
  323. foreach (T model in modelList)
  324. {
  325. DataRow dataRow = dt.NewRow();
  326. foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
  327. {
  328. dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
  329. }
  330. dt.Rows.Add(dataRow);
  331. }
  332. return dt;
  333. }
  334.  
  335. /// <summary>
  336. /// 根据实体类得到表结构
  337. /// </summary>
  338. /// <param name="model">实体类</param>
  339. /// <returns></returns>
  340. private DataTable CreateData(T model)
  341. {
  342. DataTable dataTable = new DataTable(typeof(T).Name);
  343. foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
  344. {
  345. dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
  346. }
  347. return dataTable;
  348. }
  349.  
  350. #endregion
  351. }
  352. }

再家一个主要的T4文件,命名为 Entity.tt

  1. <#@ include file="$(ProjectDir)Entity/DbHelper.ttinclude"#>
  2. using System;
  3. using MySql.Data.MySqlClient;
  4. using System.Data;
  5. using System.Collections.Generic;
  6. namespace ToolSite.Entity
  7. {
  8. public class Config
  9. {
  10. public static string DefaultDb = "<#=config.DbDatabase#>";
  11. public static string ConnStr = "<#=config.ConnectionString#>";
  12. }
  13.  
  14. <#foreach(var table in DbHelper.GetDbTables(config.ConnectionString, config.DbDatabase)){#>
  15. <# string tableName = DbHelper.ToSplitFirstUpper(table.TableName); #>
  16. public partial class <#=tableName#>
  17. {
  18. #region Field
  19. <# foreach(DbColumn column in DbHelper.GetDbColumns(config.ConnectionString, config.DbDatabase, table.TableName)){#>
  20. /// <summary>
  21. /// <#= column.Comment#>
  22. /// </summary>
  23. public <#= column.CSharpType#> <#=DbHelper.ToSplitFirstUpper(column.Field)#> { get; set; }
  24. <#}#> #endregion
  25.  
  26. public int Save()
  27. {
  28. <#=DbHelper.GetParameter(config.ConnectionString, config.DbDatabase, table.TableName, false)#>
  29. string sql = "<#=DbHelper.GetInsertSql(config.ConnectionString, config.DbDatabase, table.TableName)#>";
  30. return DBHelper.NoneQuery(sql, paras);
  31. }
  32.  
  33. public int Update()
  34. {
  35.  
  36. <#=DbHelper.GetParameter(config.ConnectionString, config.DbDatabase, table.TableName, true)#>
  37. string sql = "<#=DbHelper.GetUpdateSql(config.ConnectionString, config.DbDatabase, table.TableName)#>";
  38. return DBHelper.NoneQuery(sql, paras);
  39.  
  40. }
  41.  
  42. public static int Delete(int id)
  43. {
  44. string sql = string.Format("DELETE FROM <#=table.TableName#> WHERE id = {0}", id);
  45. return DBHelper.NoneQuery(sql);
  46.  
  47. }
  48.  
  49. public static <#=tableName#> GetById(int id)
  50. {
  51. string sql = string.Format("SELECT * FROM <#=table.TableName#> WHERE id = {0}", id);
  52. DataTable table = DBHelper.GetDateTable(sql);
  53. List<<#=tableName#>> list = new DatatableFill<<#=tableName#>>().FillModel(table);
  54. //List<<#=tableName#>> list = Mapper.DynamicMap<IDataReader, List<<#=tableName#>>>(table.CreateDataReader());
  55. if (list == null || list.Count == ) return null;
  56. return list[];
  57. }
  58.  
  59. public static List<<#=tableName#>> GetList()
  60. {
  61. string sql = "SELECT * FROM <#=table.TableName#>";
  62. DataTable table = DBHelper.GetDateTable(sql);
  63. List<<#=tableName#>> list = new DatatableFill<<#=tableName#>>().FillModel(table);
  64. //List<<#=tableName#>> list = Mapper.DynamicMap<IDataReader, List<<#=tableName#>>>(table.CreateDataReader());
  65. return list;
  66.  
  67. }
  68.  
  69. public static List<<#=tableName#>> Find(string where)
  70. {
  71. string sql = string.Format("SELECT * FROM <#=table.TableName#> WHERE {0};", where);
  72. DataTable table = DBHelper.GetDateTable(sql);
  73. return new DatatableFill<<#=tableName#>>().FillModel(table);
  74. }
  75.  
  76. public static List<<#=tableName#>> Find(string field, string prop)
  77. {
  78. return Find(string.Format(" {0} = '{1}' ", field, prop));
  79.  
  80. }
  81.  
  82. public static bool Exist(string field, string prop)
  83. {
  84. int n = Count(field, prop);
  85. return n > ? true : false;
  86. }
  87.  
  88. public static int Count(string where)
  89. {
  90. string sql = string.Format("SELECT COUNT(1) FROM <#=table.TableName#> WHERE {0}", where);
  91. DataTable table = DBHelper.GetDateTable(sql);
  92. return Convert.ToInt32(table.Rows[][]);
  93. }
  94.  
  95. public static int Count(string field, string prop)
  96. {
  97. return Count(string.Format(" {0} = '{1}' ", field, prop));
  98. }
  99.  
  100. public static int Count()
  101. {
  102. return Count(" 1 = 1 ");
  103. }
  104.  
  105. public static List<<#=tableName#>> Find(int index, int size, ref int count)
  106. {
  107. count = Count(" 1 = 1 ");
  108. string sql = string.Format(" 1 = 1 Order by id desc LIMIT {0}, {1} ", index * size , size);
  109. return Find(sql);
  110. }
  111.  
  112. public static List<<#=tableName#>> Find(string field, string prop, int index, int size, ref int count)
  113. {
  114. count = Count(field, prop);
  115. string sql = string.Format(" {0} = {1} Order by id desc LIMIT {2}, {3} ", field, prop, index, size);
  116. return Find(sql);
  117. }
  118. }
  119.  
  120. <#}#>
  121. }
  122.  
  123. <#+
  124. class config
  125. {
  126. public static readonly string ConnectionString = "Server=127.0.0.1;Database=toolsite;Uid=root;Pwd=root;";
  127. public static readonly string DbDatabase = "toolsite";
  128. }
  129. #>

你需要改的是最后那个文件的这个位置

  1. class config
  2. {
  3. public static readonly string ConnectionString = "Server=127.0.0.1;Database=toolsite;Uid=root;Pwd=root;";
  4. public static readonly string DbDatabase = "toolsite";
  5. }

怎么改我相信你懂的,点击下保存,你的实体类,跟数据库操作就生成了

最后生成的代码是这样子的,还是蛮粗糙的,如果你愿意改改,我相信会更好的!!!

  1. using System;
  2. using MySql.Data.MySqlClient;
  3. using System.Data;
  4. using System.Collections.Generic;
  5. namespace ToolSite.Entity
  6. {
  7. public class Config
  8. {
  9. public static string DefaultDb = "toolsite";
  10. public static string ConnStr = "Server=127.0.0.1;Database=toolsite;Uid=root;Pwd=root;";
  11. }
  12.  
  13. public partial class PageInfo
  14. {
  15. #region Field
  16. /// <summary>
  17. ///
  18. /// </summary>
  19. public int Id { get; set; }
  20. /// <summary>
  21. ///
  22. /// </summary>
  23. public int SiteId { get; set; }
  24. /// <summary>
  25. ///
  26. /// </summary>
  27. public int ParentId { get; set; }
  28. /// <summary>
  29. ///
  30. /// </summary>
  31. public string FileName { get; set; }
  32. /// <summary>
  33. ///
  34. /// </summary>
  35. public string Content { get; set; }
  36. /// <summary>
  37. ///
  38. /// </summary>
  39. public string Title { get; set; }
  40. /// <summary>
  41. ///
  42. /// </summary>
  43. public string Keywords { get; set; }
  44. /// <summary>
  45. ///
  46. /// </summary>
  47. public string Description { get; set; }
  48. /// <summary>
  49. ///
  50. /// </summary>
  51. public string H1 { get; set; }
  52. #endregion
  53.  
  54. public int Save()
  55. {
  56. MySqlParameter[] paras = new MySqlParameter[] {
  57. new MySqlParameter("site_id", this.SiteId),
  58. new MySqlParameter("parent_id", this.ParentId),
  59. new MySqlParameter("file_name", this.FileName),
  60. new MySqlParameter("content", this.Content),
  61. new MySqlParameter("title", this.Title),
  62. new MySqlParameter("keywords", this.Keywords),
  63. new MySqlParameter("description", this.Description),
  64. new MySqlParameter("h1", this.H1)
  65. };
  66.  
  67. string sql = "INSERT INTO page_info(site_id, parent_id, file_name, content, title, keywords, description, h1) VALUES(?site_id, ?parent_id, ?file_name, ?content, ?title, ?keywords, ?description, ?h1)";
  68. return DBHelper.NoneQuery(sql, paras);
  69. }
  70.  
  71. public int Update()
  72. {
  73.  
  74. MySqlParameter[] paras = new MySqlParameter[] {
  75. new MySqlParameter("id", this.Id),
  76. new MySqlParameter("site_id", this.SiteId),
  77. new MySqlParameter("parent_id", this.ParentId),
  78. new MySqlParameter("file_name", this.FileName),
  79. new MySqlParameter("content", this.Content),
  80. new MySqlParameter("title", this.Title),
  81. new MySqlParameter("keywords", this.Keywords),
  82. new MySqlParameter("description", this.Description),
  83. new MySqlParameter("h1", this.H1)
  84. };
  85.  
  86. string sql = "UPDATE page_info SET site_id = ?site_id, parent_id = ?parent_id, file_name = ?file_name, content = ?content, title = ?title, keywords = ?keywords, description = ?description, h1 = ?h1 WHERE id = ?id";
  87. return DBHelper.NoneQuery(sql, paras);
  88.  
  89. }
  90.  
  91. public static int Delete(int id)
  92. {
  93. string sql = string.Format("DELETE FROM page_info WHERE id = {0}", id);
  94. return DBHelper.NoneQuery(sql);
  95.  
  96. }
  97.  
  98. public static PageInfo GetById(int id)
  99. {
  100. string sql = string.Format("SELECT * FROM page_info WHERE id = {0}", id);
  101. DataTable table = DBHelper.GetDateTable(sql);
  102. List<PageInfo> list = new DatatableFill<PageInfo>().FillModel(table);
  103. //List<PageInfo> list = Mapper.DynamicMap<IDataReader, List<PageInfo>>(table.CreateDataReader());
  104. if (list == null || list.Count == ) return null;
  105. return list[];
  106. }
  107.  
  108. public static List<PageInfo> GetList()
  109. {
  110. string sql = "SELECT * FROM page_info";
  111. DataTable table = DBHelper.GetDateTable(sql);
  112. List<PageInfo> list = new DatatableFill<PageInfo>().FillModel(table);
  113. //List<PageInfo> list = Mapper.DynamicMap<IDataReader, List<PageInfo>>(table.CreateDataReader());
  114. return list;
  115.  
  116. }
  117.  
  118. public static List<PageInfo> Find(string where)
  119. {
  120. string sql = string.Format("SELECT * FROM page_info WHERE {0};", where);
  121. DataTable table = DBHelper.GetDateTable(sql);
  122. return new DatatableFill<PageInfo>().FillModel(table);
  123. }
  124.  
  125. public static List<PageInfo> Find(string field, string prop)
  126. {
  127. return Find(string.Format(" {0} = '{1}' ", field, prop));
  128.  
  129. }
  130.  
  131. public static bool Exist(string field, string prop)
  132. {
  133. int n = Count(field, prop);
  134. return n > ? true : false;
  135. }
  136.  
  137. public static int Count(string where)
  138. {
  139. string sql = string.Format("SELECT COUNT(1) FROM page_info WHERE {0}", where);
  140. DataTable table = DBHelper.GetDateTable(sql);
  141. return Convert.ToInt32(table.Rows[][]);
  142. }
  143.  
  144. public static int Count(string field, string prop)
  145. {
  146. return Count(string.Format(" {0} = '{1}' ", field, prop));
  147. }
  148.  
  149. public static int Count()
  150. {
  151. return Count(" 1 = 1 ");
  152. }
  153.  
  154. public static List<PageInfo> Find(int index, int size, ref int count)
  155. {
  156. count = Count(" 1 = 1 ");
  157. string sql = string.Format(" 1 = 1 Order by id desc LIMIT {0}, {1} ", index * size , size);
  158. return Find(sql);
  159. }
  160.  
  161. public static List<PageInfo> Find(string field, string prop, int index, int size, ref int count)
  162. {
  163. count = Count(field, prop);
  164. string sql = string.Format(" {0} = {1} Order by id desc LIMIT {2}, {3} ", field, prop, index, size);
  165. return Find(sql);
  166. }
  167. }
  168.  
  169. public partial class SiteInfo
  170. {
  171. #region Field
  172. /// <summary>
  173. ///
  174. /// </summary>
  175. public int Id { get; set; }
  176. /// <summary>
  177. ///
  178. /// </summary>
  179. public string Name { get; set; }
  180. /// <summary>
  181. ///
  182. /// </summary>
  183. public string Template { get; set; }
  184. #endregion
  185.  
  186. public int Save()
  187. {
  188. MySqlParameter[] paras = new MySqlParameter[] {
  189. new MySqlParameter("name", this.Name),
  190. new MySqlParameter("template", this.Template)
  191. };
  192.  
  193. string sql = "INSERT INTO site_info(name, template) VALUES(?name, ?template)";
  194. return DBHelper.NoneQuery(sql, paras);
  195. }
  196.  
  197. public int Update()
  198. {
  199.  
  200. MySqlParameter[] paras = new MySqlParameter[] {
  201. new MySqlParameter("id", this.Id),
  202. new MySqlParameter("name", this.Name),
  203. new MySqlParameter("template", this.Template)
  204. };
  205.  
  206. string sql = "UPDATE site_info SET name = ?name, template = ?template WHERE id = ?id";
  207. return DBHelper.NoneQuery(sql, paras);
  208.  
  209. }
  210.  
  211. public static int Delete(int id)
  212. {
  213. string sql = string.Format("DELETE FROM site_info WHERE id = {0}", id);
  214. return DBHelper.NoneQuery(sql);
  215.  
  216. }
  217.  
  218. public static SiteInfo GetById(int id)
  219. {
  220. string sql = string.Format("SELECT * FROM site_info WHERE id = {0}", id);
  221. DataTable table = DBHelper.GetDateTable(sql);
  222. List<SiteInfo> list = new DatatableFill<SiteInfo>().FillModel(table);
  223. //List<SiteInfo> list = Mapper.DynamicMap<IDataReader, List<SiteInfo>>(table.CreateDataReader());
  224. if (list == null || list.Count == ) return null;
  225. return list[];
  226. }
  227.  
  228. public static List<SiteInfo> GetList()
  229. {
  230. string sql = "SELECT * FROM site_info";
  231. DataTable table = DBHelper.GetDateTable(sql);
  232. List<SiteInfo> list = new DatatableFill<SiteInfo>().FillModel(table);
  233. //List<SiteInfo> list = Mapper.DynamicMap<IDataReader, List<SiteInfo>>(table.CreateDataReader());
  234. return list;
  235.  
  236. }
  237.  
  238. public static List<SiteInfo> Find(string where)
  239. {
  240. string sql = string.Format("SELECT * FROM site_info WHERE {0};", where);
  241. DataTable table = DBHelper.GetDateTable(sql);
  242. return new DatatableFill<SiteInfo>().FillModel(table);
  243. }
  244.  
  245. public static List<SiteInfo> Find(string field, string prop)
  246. {
  247. return Find(string.Format(" {0} = '{1}' ", field, prop));
  248.  
  249. }
  250.  
  251. public static bool Exist(string field, string prop)
  252. {
  253. int n = Count(field, prop);
  254. return n > ? true : false;
  255. }
  256.  
  257. public static int Count(string where)
  258. {
  259. string sql = string.Format("SELECT COUNT(1) FROM site_info WHERE {0}", where);
  260. DataTable table = DBHelper.GetDateTable(sql);
  261. return Convert.ToInt32(table.Rows[][]);
  262. }
  263.  
  264. public static int Count(string field, string prop)
  265. {
  266. return Count(string.Format(" {0} = '{1}' ", field, prop));
  267. }
  268.  
  269. public static int Count()
  270. {
  271. return Count(" 1 = 1 ");
  272. }
  273.  
  274. public static List<SiteInfo> Find(int index, int size, ref int count)
  275. {
  276. count = Count(" 1 = 1 ");
  277. string sql = string.Format(" 1 = 1 Order by id desc LIMIT {0}, {1} ", index * size , size);
  278. return Find(sql);
  279. }
  280.  
  281. public static List<SiteInfo> Find(string field, string prop, int index, int size, ref int count)
  282. {
  283. count = Count(field, prop);
  284. string sql = string.Format(" {0} = {1} Order by id desc LIMIT {2}, {3} ", field, prop, index, size);
  285. return Find(sql);
  286. }
  287. }
  288.  
  289. }

T4生成实体和简单的CRUD操作的更多相关文章

  1. T4 生成实体和简单的CRUD操作

    <#@ template debug="false" hostspecific="false" language="C#" #> ...

  2. 8天掌握EF的Code First开发系列之2 简单的CRUD操作

    本文出自8天掌握EF的Code First开发系列,经过自己的实践整理出来. 本篇目录 创建控制台项目 根据.Net中的类来创建数据库 简单的CRUD操作 数据库模式更改介绍 本章小结 本人的实验环境 ...

  3. ASP.NET Core MVC+Layui使用EF Core连接MySQL执行简单的CRUD操作

    前言: 本章主要通过一个完整的示例讲解ASP.NET Core MVC+EF Core对MySQL数据库进行简单的CRUD操作,希望能够为刚入门.NET Core的小伙伴们提供一个完整的参考实例.关于 ...

  4. 【SSH三大框架】Hibernate基础第五篇:利用Hibernate完毕简单的CRUD操作

    这里利用Hibernate操作数据库完毕简单的CRUD操作. 首先,我们须要先写一个javabean: package cn.itcast.domain; import java.util.Date; ...

  5. hibernate入门-基本配置及简单的crud操作

    框架来说主要是需要写大量的配置文件,hibernate相比mybatis来说更强大,移植性更好: 1.类和数据库的映射配置:配置文件命名一般--类名.hbm.xml (user.hbm.xml),与实 ...

  6. 懒人小工具:T4生成实体类Model,Insert,Select,Delete以及导出Excel的方法

    由于最近公司在用webform开发ERP,用到大量重复机械的代码,之前写了篇文章,懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法,但是有人觉得这种方法 ...

  7. T4生成实体,单张表和多张表

    # 使用说明 . 把T4目录放在项目的根目录 . 配置连接字符串,在tt文件的最底部 . generateAllEntity.tt生成全部的实体类 . generateSingleEntityByNa ...

  8. Spring Data MongoDB 一:入门篇(环境搭建、简单的CRUD操作)

    一.简介 Spring Data  MongoDB 项目提供与MongoDB文档数据库的集成.Spring Data MongoDB POJO的关键功能区域为中心的模型与MongoDB的DBColle ...

  9. elasticsearch入门(简单的crud操作)

    记录一下,elasticsearch从创建索引到插入数据的一个crud操作. 一.创建索引 curl -XPUT "http://192.168.99.1:9200/productindex ...

随机推荐

  1. WinEdt && LaTex(三)—— 宏包

    amsmath:最常用的数学宏包 1. bm:bold math 数学字体加粗 \documentclass{article} \usepackage{bm} \begin{document} \[ ...

  2. 微信小程序--实现图片上传

    前端: 微信开发者工具 后端:.Net 服务器:阿里云 这里介绍微信小程序如何实现上传图片到自己的服务器上 前端代码 data: { productInfo: {} }, //添加Banner bin ...

  3. xmarin live player 连接 IOS以及安卓实现实时效果查看

    原文:xmarin live player 连接 IOS以及安卓实现实时效果查看 在之前有介绍过xamarin 单独IOS项目开发的运行环境搭建,但是这段时间我看到了xmarin forms 3.0  ...

  4. Matlab随笔之判别分析

    原文:Matlab随笔之判别分析 从概率论角度,判别分析是根据所给样本数据,对所给的未分类数据进行分类. 如下表,已知有t个样本数据,每个数据关于n个量化特征有一个值,又已知该样本数据的分类,据此,求 ...

  5. Google CFO 辞职信

    Google CFO 辞职信   After nearly 7 years as CFO, I will be retiring from Google to spend more time with ...

  6. .net core响应缓存

    按照官网资料操作无效,这里使用https://github.com/speige/AspNetCore.ResponseCaching.Extensions的扩展包 安装AspNetCore.Resp ...

  7. C++中一个class类对象占用多少内字节(7个例子,很清楚)

    一个空的class在内存中多少字节?如果加入一个成员函数后是多大?这个成员函数存储在内存中什么部分? 一个Class对象需要占用多大的内存空间.最权威的结论是: *非静态成员变量总合. *加上编译器为 ...

  8. TinyMCE插件CodeSample前后端应用

    后端使用插件CodeSample方法: <html> <textarea id="editor_id" name="content" plac ...

  9. 批处理(bat)实现SQLServer数据库备份与还原

    原文:批处理(bat)实现SQLServer数据库备份与还原 备份数据库.bat @echo off set path=%path%;C:\Program Files (x86)\Microsoft ...

  10. WIN10以后如果Manifest中不写支持WIN10的话,获取版本号的API获取的是6

    if TOSVersion.Major = 10 then  // 高版本的Delphi(比如Berlin)可以这样写 ShowMessage('Windows 10'); 或者: if Win32M ...