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


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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Configuration;
using MySql.Data.MySqlClient;
using System.Reflection;
using System.Text;

namespace ToolSite.Entity
{

    public class DBHelper
    {
        //加入�到配置文件的<configuration>节点中
        //   <connectionStrings>
        //       <!--改写数据库名,登陆名,password-->
        //        <add name="conStr" connectionString="Data Source=.;Initial Catalog=;User ID=;Password="/>
        //  
        //   </connectionStrings>
        //<appSettings>
        //      <add key="dbConnection" value="server=192.168.1.111\SQL2005;database=GCUMS;UID=sa;PWD=sa;max pool size=20000;Pooling=true;"/>
        //  </appSettings>
        //先加入�configuration引用,引入命名空间
        //private static readonly string conStr = ConfigurationManager.AppSettings["connstr"]; 
        //private static readonly string conStr = Config.ConnStr;
        /// <summary>
        /// 获得连接字符串
        /// </summary>
        /// <returns></returns>
        public static MySqlConnection getConn()
        {
            return new MySqlConnection(Config.ConnStr);
        }
        /// <summary>
        /// 查询获得首行首列的值,格式化SQL语句
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static object Scalar(String sql)
        {
            using (MySqlConnection con = getConn())
            {
                try
                {
                    MySqlCommand com = new MySqlCommand(sql, con);
                    con.Open();
                    return com.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 查询获得首行首列的值 參数化sql语句
        /// </summary>
        /// <param name="paras">參数数组</param>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public static object Scalar(string sql, MySqlParameter[] paras)
        {
            using (MySqlConnection con = getConn())
            {
                try
                {
                    MySqlCommand com = new MySqlCommand(sql, con);
                    con.Open();
                    if (paras != null) //假设參数
                    {
                        com.Parameters.AddRange(paras);
                    }
                    return com.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    throw ex;

                }
            }
        }

        /// <summary>
        /// 增删改操作,返回受影响的行数,格式化SQL语句
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int NoneQuery(String sql)
        {

            using (MySqlConnection conn = getConn())
            {
                conn.Open();
                using (MySqlCommand comm = new MySqlCommand(sql, conn))
                {
                    return comm.ExecuteNonQuery();
                }

            }
        }
        /// <summary>
        /// 增删改操作,返回受影响的行数 存储过程
        /// </summary>
        /// <param name="sql">存储过程名称</param>
        /// <param name="paras">參数</param>
        /// <returns></returns>
        public static int NoneQuery(String sql, MySqlParameter[] paras)
        {
            using (MySqlConnection conn = getConn())
            {
                conn.Open();
                using (MySqlCommand comm = new MySqlCommand(sql, conn))
                {
                    comm.Parameters.AddRange(paras);
                    return comm.ExecuteNonQuery();
                }

            }
        }
        /// <summary>
        /// 查询操作,返回一个数据表
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetDateTable(String sql)
        {
            using (MySqlConnection con = getConn())
            {
                DataTable dt = new DataTable();
                try
                {
                    MySqlDataAdapter sda = new MySqlDataAdapter(sql, con);
                    sda.Fill(dt);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return dt;
            }
        }
        /// <summary>
        ///  查询操作,返回一个数据表,存储过程
        /// </summary>
        /// <param name="sp_Name">存储过程名称</param>
        /// <param name="paras">存储过程參数</param>
        /// <returns></returns>
        public static DataTable GetDateTable(String sql, MySqlParameter[] paras)
        {
            using (MySqlConnection con = getConn())
            {
                DataTable dt = new DataTable();
                try
                {
                    MySqlCommand com = new MySqlCommand(sql, con);
                    com.Parameters.AddRange(paras);
                    MySqlDataAdapter sda = new MySqlDataAdapter(com);
                    sda.Fill(dt);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return dt;
            }
        }



    }

    /// <summary>
    /// DataTable与实体类互相转换
    /// </summary>
    /// <typeparam name="T">实体类</typeparam>
    public class DatatableFill<T> where T : new()
    {
        #region DataTable转换成实体类
        /// <summary>
        /// 填充对象列表:用DataSet的第一个表填充实体类
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <returns></returns>
        public List<T> FillModel(DataSet ds)
        {
            if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
            {
                return new List<T>();
            }
            else
            {
                return FillModel(ds.Tables[0]);
            }
        }

        /// <summary>  
        /// 填充对象列表:用DataSet的第index个表填充实体类
        /// </summary>  
        public List<T> FillModel(DataSet ds, int index)
        {
            if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == 0)
            {
                return new List<T>() ;
            }
            else
            {
                return FillModel(ds.Tables[index]);
            }
        }



        /// <summary>  
        /// 填充对象列表:用DataTable填充实体类
        /// </summary>  
        public List<T> FillModel(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return new List<T>();
            }
            List<T> modelList = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                //T model = (T)Activator.CreateInstance(typeof(T));  
                T model = new T();
                for (int i = 0; i < dr.Table.Columns.Count; i++)
                {
                    PropertyInfo propertyInfo = model.GetType().GetProperty(ToSplitFirstUpper(dr.Table.Columns[i].ColumnName));
                    if (propertyInfo != null && dr[i] != DBNull.Value)
                        propertyInfo.SetValue(model, dr[i], null);
                }

                modelList.Add(model);
            }
            return modelList;
        }

        /// <summary>  
        /// 填充对象:用DataRow填充实体类
        /// </summary>  
        public T FillModel(DataRow dr)
        {
            if (dr == null)
            {
                return default(T);
            }

            //T model = (T)Activator.CreateInstance(typeof(T));  
            T model = new T();

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                PropertyInfo propertyInfo = model.GetType().GetProperty(ToSplitFirstUpper(dr.Table.Columns[i].ColumnName));
                if (propertyInfo != null && dr[i] != DBNull.Value)
                    propertyInfo.SetValue(model, dr[i], null);
            }
            return model;
        }

        // 去下划线,转大写
        public static string ToSplitFirstUpper(string file)
        {
            string[] words = file.Split('_');
            StringBuilder firstUpperWorld = new StringBuilder();
            foreach (string word in words)
            {
                string firstUpper = ToFirstUpper(word);
                firstUpperWorld.Append(firstUpper);
            }
            string firstUpperFile = firstUpperWorld.ToString().TrimEnd(new char[] { '_' });
            return firstUpperFile;
        }

        // 将字符串设置成首字母大写
        public static string ToFirstUpper(string field)
        {
            string first = field.Substring(0, 1).ToUpperInvariant();
            string result = first;
            if (field.Length > 1)
            {
                string after = field.Substring(1);
                result = first + after;
            }
            return result;
        }
        #endregion

        #region 实体类转换成DataTable

        /// <summary>
        /// 实体类转换成DataSet
        /// </summary>
        /// <param name="modelList">实体类列表</param>
        /// <returns></returns>
        public DataSet FillDataSet(List<T> modelList)
        {
            if (modelList == null || modelList.Count == 0)
            {
                return null;
            }
            else
            {
                DataSet ds = new DataSet();
                ds.Tables.Add(FillDataTable(modelList));
                return ds;
            }
        }

        /// <summary>
        /// 实体类转换成DataTable
        /// </summary>
        /// <param name="modelList">实体类列表</param>
        /// <returns></returns>
        public DataTable FillDataTable(List<T> modelList)
        {
            if (modelList == null || modelList.Count == 0)
            {
                return null;
            }
            DataTable dt = CreateData(modelList[0]);

            foreach (T model in modelList)
            {
                DataRow dataRow = dt.NewRow();
                foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
                {
                    dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
                }
                dt.Rows.Add(dataRow);
            }
            return dt;
        }

        /// <summary>
        /// 依据实体类得到表结构
        /// </summary>
        /// <param name="model">实体类</param>
        /// <returns></returns>
        private DataTable CreateData(T model)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);
            foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
            {
                dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
            }
            return dataTable;
        }

        #endregion
    }
}


再家一个基本的T4文件,命名为 Entity.tt



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

    class config
    {
        public static readonly string ConnectionString = "Server=127.0.0.1;Database=toolsite;Uid=root;Pwd=root;";
        public static readonly string DbDatabase = "toolsite";
    }

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

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

using System;
using MySql.Data.MySqlClient;
using System.Data;
using System.Collections.Generic;
namespace ToolSite.Entity
{
	public class Config
	{
		public static string DefaultDb = "toolsite";
		public static string ConnStr = "Server=127.0.0.1;Database=toolsite;Uid=root;Pwd=root;";
	}
		
	public partial class PageInfo
    {
		#region Field
		/// <summary>
        /// 
        /// </summary>
		public int Id { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public int SiteId { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public int ParentId { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public string FileName { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public string Content { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public string Title { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public string Keywords { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public string Description { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public string H1 { get; set; }
		#endregion

		public int Save()
		{
			MySqlParameter[] paras = new MySqlParameter[] { 
				 new MySqlParameter("site_id", this.SiteId),
				 new MySqlParameter("parent_id", this.ParentId),
				 new MySqlParameter("file_name", this.FileName),
				 new MySqlParameter("content", this.Content),
				 new MySqlParameter("title", this.Title),
				 new MySqlParameter("keywords", this.Keywords),
				 new MySqlParameter("description", this.Description),
				 new MySqlParameter("h1", this.H1)
			};

			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)";
		return DBHelper.NoneQuery(sql, paras);
		}
		
		public int Update()
        {

            MySqlParameter[] paras = new MySqlParameter[] { 
				 new MySqlParameter("id", this.Id),
				 new MySqlParameter("site_id", this.SiteId),
				 new MySqlParameter("parent_id", this.ParentId),
				 new MySqlParameter("file_name", this.FileName),
				 new MySqlParameter("content", this.Content),
				 new MySqlParameter("title", this.Title),
				 new MySqlParameter("keywords", this.Keywords),
				 new MySqlParameter("description", this.Description),
				 new MySqlParameter("h1", this.H1)
			};

			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";
            return DBHelper.NoneQuery(sql, paras);

        }

		public static int Delete(int id)
        {
            string sql = string.Format("DELETE FROM page_info WHERE id = {0}", id);
            return DBHelper.NoneQuery(sql);

        }

		public static PageInfo GetById(int id)
        {
            string sql = string.Format("SELECT * FROM page_info WHERE id = {0}", id);
            DataTable table = DBHelper.GetDateTable(sql);
			List<PageInfo> list = new DatatableFill<PageInfo>().FillModel(table);
            //List<PageInfo> list = Mapper.DynamicMap<IDataReader, List<PageInfo>>(table.CreateDataReader());
            if (list == null || list.Count == 0) return null;
            return list[0];
        }

		public static List<PageInfo> GetList()
        {
            string sql = "SELECT * FROM page_info";
            DataTable table = DBHelper.GetDateTable(sql);
			List<PageInfo> list = new DatatableFill<PageInfo>().FillModel(table);
            //List<PageInfo> list = Mapper.DynamicMap<IDataReader, List<PageInfo>>(table.CreateDataReader());
            return list;

        }

		public static List<PageInfo> Find(string where)
        {
            string sql = string.Format("SELECT * FROM page_info WHERE {0};", where);
            DataTable table = DBHelper.GetDateTable(sql);
            return new DatatableFill<PageInfo>().FillModel(table);
        }

        public static List<PageInfo> Find(string field, string prop)
        {
            return Find(string.Format(" {0} = '{1}' ", field, prop));

        }

        public static bool Exist(string field, string prop)
        {
            int n = Count(field, prop);
            return n > 0 ? true : false;
        }

        public static int Count(string where)
        {
            string sql = string.Format("SELECT COUNT(1) FROM page_info WHERE {0}", where);
            DataTable table = DBHelper.GetDateTable(sql);
            return Convert.ToInt32(table.Rows[0][0]);
        }

        public static int Count(string field, string prop)
        {
            return Count(string.Format(" {0} = '{1}' ", field, prop));
        }

        public static int Count()
        {
            return Count(" 1 = 1 ");
        }

        public static List<PageInfo> Find(int index, int size, ref int count)
        {
            count = Count(" 1 = 1 ");
            string sql = string.Format(" 1 = 1 Order by id desc  LIMIT {0}, {1} ", index * size , size);
            return Find(sql);
        }

        public static List<PageInfo> Find(string field, string prop, int index, int size, ref int count)
        {
            count = Count(field, prop);
            string sql = string.Format(" {0} = {1} Order by id desc LIMIT {2}, {3} ", field, prop, index, size);
            return Find(sql);
        }
    }

	public partial class SiteInfo
    {
		#region Field
		/// <summary>
        /// 
        /// </summary>
		public int Id { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public string Name { get; set; }
		/// <summary>
        /// 
        /// </summary>
		public string Template { get; set; }
		#endregion

		public int Save()
		{
			MySqlParameter[] paras = new MySqlParameter[] { 
				 new MySqlParameter("name", this.Name),
				 new MySqlParameter("template", this.Template)
			};

			string sql = "INSERT INTO site_info(name, template) VALUES(?name, ?template)";
		return DBHelper.NoneQuery(sql, paras);
		}
		
		public int Update()
        {

            MySqlParameter[] paras = new MySqlParameter[] { 
				 new MySqlParameter("id", this.Id),
				 new MySqlParameter("name", this.Name),
				 new MySqlParameter("template", this.Template)
			};

			string sql = "UPDATE site_info SET name = ?name, template = ?template WHERE id = ?id";
            return DBHelper.NoneQuery(sql, paras);

        }

		public static int Delete(int id)
        {
            string sql = string.Format("DELETE FROM site_info WHERE id = {0}", id);
            return DBHelper.NoneQuery(sql);

        }

		public static SiteInfo GetById(int id)
        {
            string sql = string.Format("SELECT * FROM site_info WHERE id = {0}", id);
            DataTable table = DBHelper.GetDateTable(sql);
			List<SiteInfo> list = new DatatableFill<SiteInfo>().FillModel(table);
            //List<SiteInfo> list = Mapper.DynamicMap<IDataReader, List<SiteInfo>>(table.CreateDataReader());
            if (list == null || list.Count == 0) return null;
            return list[0];
        }

		public static List<SiteInfo> GetList()
        {
            string sql = "SELECT * FROM site_info";
            DataTable table = DBHelper.GetDateTable(sql);
			List<SiteInfo> list = new DatatableFill<SiteInfo>().FillModel(table);
            //List<SiteInfo> list = Mapper.DynamicMap<IDataReader, List<SiteInfo>>(table.CreateDataReader());
            return list;

        }

		public static List<SiteInfo> Find(string where)
        {
            string sql = string.Format("SELECT * FROM site_info WHERE {0};", where);
            DataTable table = DBHelper.GetDateTable(sql);
            return new DatatableFill<SiteInfo>().FillModel(table);
        }

        public static List<SiteInfo> Find(string field, string prop)
        {
            return Find(string.Format(" {0} = '{1}' ", field, prop));

        }

        public static bool Exist(string field, string prop)
        {
            int n = Count(field, prop);
            return n > 0 ? true : false;
        }

        public static int Count(string where)
        {
            string sql = string.Format("SELECT COUNT(1) FROM site_info WHERE {0}", where);
            DataTable table = DBHelper.GetDateTable(sql);
            return Convert.ToInt32(table.Rows[0][0]);
        }

        public static int Count(string field, string prop)
        {
            return Count(string.Format(" {0} = '{1}' ", field, prop));
        }

        public static int Count()
        {
            return Count(" 1 = 1 ");
        }

        public static List<SiteInfo> Find(int index, int size, ref int count)
        {
            count = Count(" 1 = 1 ");
            string sql = string.Format(" 1 = 1 Order by id desc  LIMIT {0}, {1} ", index * size , size);
            return Find(sql);
        }

        public static List<SiteInfo> Find(string field, string prop, int index, int size, ref int count)
        {
            count = Count(field, prop);
            string sql = string.Format(" {0} = {1} Order by id desc LIMIT {2}, {3} ", field, prop, index, size);
            return Find(sql);
        }
    }

}


相关文章: