/ dotnet

T4 模板自动生成实体类代码

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Data.OracleClient" #>
<#@ assembly name="System.Xml" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.OracleClient" #>
<#@ import namespace="System.Collections.Generic"#>
<#@ include file="ModelAuto.ttinclude"#>
<# var manager2 = new Manager(Host, GenerationEnvironment, true) { OutputPath = Path.GetDirectoryName(Host.TemplateFile)}; #>
<# 
ModelManager manager = new ModelManager();
List<string> list=manager.GetTableList();
#>

<# 
    foreach (var item in list)
    {
        string tableName=item;
        DataTable table= manager.GetTableSchema(tableName);
 #>

 <# 
        manager2.StartBlock(tableName+".cs");
 #>
using System;
using System.Data;
using System.Data.OracleClient;
namespace Model
{
    /// <summary>
    /// 数据表实体类:<#= tableName #> 
    /// </summary>
    [Serializable()]
    public class <#= tableName #>
    {
<#
foreach(DataRow row in table.Rows)
{
#>
       /// <summary>
       /// <#=row["备注"]#>
       /// </summary>     
       public <#= manager.TransFromSqlType(row["数据类型"].ToString())#> <#=row["字段名"]#>{ get; set; }
<#}
#>
    }
}

<# manager2.EndBlock(); #>

<#
    }  
 #>     
   
<# manager2.Process(true); #>

<#+
    public class ModelManager
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
       private const string CONNECTION_STRING = "****";
        /// <summary>
        /// 用户信息表名
        /// </summary>
        private const string PERSONINFO_TABLE_NAME = "****";
        /// <summary>
        /// 根据表名查询表结构信息
        /// </summary>
        private const string SELECT_SCHEMA_BY_TABLE_NAME = @"SELECT A.column_name    字段名,                                                                                           
                                                                    A.data_type      数据类型,
                                                                    A.data_length    长度,
                                                                    A.data_precision 整数位,
                                                                    A.Data_Scale     小数位,
                                                                    A.nullable       允许空值,
                                                                    A.Data_default   缺省值,
                                                                    B.comments       备注,
                                                                    A.TABLE_NAME     表名
                                                                    FROM all_tab_columns A, all_col_comments B
                                                                    WHERE a.COLUMN_NAME = b.column_name
                                                                    AND A.Table_Name = B.Table_Name
                                                                    AND A.Table_Name = 'T_ORG_DEPARTMENT'";

        /// <summary>
        /// 获得数据连接
        /// </summary>
        /// <returns></returns>
        private OracleConnection GetConnection()
        {
            return new OracleConnection(CONNECTION_STRING);
        }

        /// <summary>
        /// 得到当前用户的所有表名
        /// </summary>
        /// <returns></returns>
        public List<string> GetTableList()
        {
            string sql = "SELECT * FROM all_tables where owner = '****' and table_name = '****'";
            DataTable dt = OracleHelper.ExecuteDataTable(sql);
            List<string> list = new List<string>();
            if (dt!=null&&dt.Rows.Count>0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    list.Add(dt.Rows[i]["TABLE_NAME"].ToString());
                } 
            }
            return list;
         }

        /// <summary>
        /// 释放连接
        /// </summary>
        /// <param name="con"></param>
        private void ReleaseConnection(OracleConnection con)
        {
            if (con != null)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
        }

        public DataTable GetTableSchema(string tableName)
        {
            DataTable dt;
            using (OracleConnection con = GetConnection())
            {
                con.Open();
                OracleCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format(SELECT_SCHEMA_BY_TABLE_NAME,tableName);
                cmd.CommandType = CommandType.Text;
                OracleDataAdapter adapter = new OracleDataAdapter(cmd);
                DataSet ds = new DataSet(); 
                adapter.Fill(ds);
                dt = ds.Tables[0];
            }

            return dt;
        }

        /// <summary>
        /// SQL[不完善,需要的自己改造]
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public string TransFromSqlType(string type)
        {
            if (string.IsNullOrEmpty(type))
            {
                return string.Empty;
            }
            if (string.Equals(type, "number", StringComparison.OrdinalIgnoreCase))
            {
                return "int";
            }
            if (string.Equals(type, "date", StringComparison.OrdinalIgnoreCase))
            {
                return "DateTime";
            }
            else if (string.Equals(type, "nvarchar2", StringComparison.OrdinalIgnoreCase))
            {
                return "string";
            }
            return "string";
        }
    }
#>

<#+ 
public class OracleHelper
    {

        private static string oracleConnectionStr = "****";
        public static DataTable ExecuteDataTable(string sql, params OracleParameter[] paramList)
        {
            using (OracleConnection conn = new OracleConnection(oracleConnectionStr))
            {
                conn.Open();
                using (OracleCommand command = conn.CreateCommand())
                {
                    command.CommandText = sql;
                    command.Parameters.AddRange(paramList);
                    DataTable dt = new DataTable();
                    OracleDataAdapter adapter = new OracleDataAdapter(command);
                    adapter.Fill(dt);
                    return dt;
                }
            }
        }

        public static int ExecuteNonQuery(string sql, params OracleParameter[] paramList)
        {
            using (OracleConnection conn = new OracleConnection(oracleConnectionStr))
            {
                conn.Open();
                using (OracleCommand command = conn.CreateCommand())
                {
                    command.CommandText = sql;
                    command.Parameters.AddRange(paramList);
                    return command.ExecuteNonQuery();
                }
            }
        }

        public static object ExecuteScalar(string sql, params OracleParameter[] paramList)
        {
            using (OracleConnection conn = new OracleConnection(oracleConnectionStr))
            {
                conn.Open();
                using (OracleCommand command = conn.CreateCommand())
                {
                    command.CommandText = sql;
                    command.Parameters.AddRange(paramList);
                    return command.ExecuteScalar();
                }
            }
        }
    }

 #>

以上为oracle示例,代码保存自动生成实体代码。

参考