导航

T4

Posted on 2016-03-17 19:03  杨彬Allen  阅读(649)  评论(0编辑  收藏  举报

简介

T4全称Text Template Transformation Toolkit,是自定义代码模板。

MVC下Add View和Add Controller就是通过T4生成的(D:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 4\CodeTemplates),可以修改MVC下的T4模板,比如加个Title,引用一个css等等。

 

自定义MVC之DataFactory

 这个类库用来动态匹配数据库和表

 

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace Biz.Framework.DataFactory
{
    public class DBSchemaFactory
    {
        private static string databaseType = "SqlServer";
        
        public static IDBSchema GetDBSchema()
        {
            IDBSchema dbSchema;
            switch (databaseType)
            {
                case "SqlServer":
                    dbSchema = new SqlServerSchema();
                    break;
                //Todo:待补MySQL,Oracle
                default: throw new ArgumentException("The input argument of DatabaseType is invalid!");
            }
            return dbSchema;
        }
    }

    public class SqlServerSchema : IDBSchema
    {
        public string ConnectionString = "Data Source=.;Initial Catalog=MyTestDB;Persist Security Info=True;User ID=sa;Password=1qaz2wsx~;";
        public SqlConnection conn;
        public SqlServerSchema()
        {
            conn = new SqlConnection(ConnectionString);
            conn.Open();
        }
        public List<string> GetTablesList()
        {
            DataTable dt = conn.GetSchema("Tables");
            Dispose();
            List<string> list = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(row["TABLE_NAME"].ToString());
            }
            return list;
        }
        public Table GetTableMetadata(string tableName)
        {
            string selectCmdText = string.Format("SELECT * FROM {0}", tableName);
            SqlCommand command = new SqlCommand(selectCmdText, conn);
            SqlDataAdapter ad = new SqlDataAdapter(command);
            System.Data.DataSet ds = new DataSet();
            ad.FillSchema(ds, SchemaType.Mapped, tableName);
            Dispose();
            Table table = new Table(ds.Tables[0]);
            return table;
        }
        public void Dispose()
        {
            if (conn != null)
                conn.Close();
        }
    }
}
DBSchemaFactory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Biz.Framework.DataFactory
{
    public class GeneratorHelper
    {
        public static readonly string StringType = "String";
        public static readonly string DateTimeType = "DateTime";
        public static string GetQuesMarkByType(string typeName)
        {
            string result = typeName;
            if (typeName == DateTimeType)
            {
                result += "?";
            }
            return result;
        }
    }
}
GeneratorHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Biz.Framework.DataFactory
{
    public interface IDBSchema : IDisposable
    {
        List<string> GetTablesList();
        Table GetTableMetadata(string tableName);
    }
}
IDBSchema
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Biz.Framework.DataFactory
{
    public class Table
    {
        public Table(DataTable t)
        {
            this.PKs = this.GetPKList(t);
            this.Columns = this.GetColumnList(t);
            this.ColumnTypeNames = this.SetColumnNames();
        }
        public List<Column> PKs;
        public List<Column> Columns;
        public string ColumnTypeNames;
        public List<Column> GetPKList(DataTable dt)
        {
            List<Column> list = new List<Column>();
            Column c = null;
            if (dt.PrimaryKey.Length > 0)
            {
                list = new List<Column>();
                foreach (DataColumn dc in dt.PrimaryKey)
                {
                    c = new Column(dc); 
                    list.Add(c);
                }
            }
            return list;
        }
        private List<Column> GetColumnList(DataTable dt)
        {
            List<Column> list = new List<Column>();
            Column c = null;
            foreach (DataColumn dc in dt.Columns)
            {
                c = new Column(dc);
                list.Add(c);
            }
            return list;
        }
        private string SetColumnNames()
        {
            List<string> list = new List<string>();
            foreach (Column c in this.Columns)
            {
                list.Add(string.Format("{0} {1}", c.TypeName, c.LowerColumnName));
            }
            return string.Join(",", list.ToArray());
        }
    }

    public class Column
    {
        DataColumn columnBase;
        public Column(DataColumn columnBase)
        {
            this.columnBase = columnBase;
        }
        public string ColumnName
        {
            get { return this.columnBase.ColumnName; }
        }
        public string MaxLength
        {
            get { return this.columnBase.MaxLength.ToString(); }
        }
        public string TypeName
        {
            get
            {
                string result = string.Empty;
                if (this.columnBase.DataType.Name == "Guid")//for mysql,因为对于MYSQL如果是CHAR(36),类型自动为Guid
                    result = "String";
                else
                    result = this.columnBase.DataType.Name;
                return result;
            }
        }
        public bool AllowDBNull
        {
            get
            {
                return this.columnBase.AllowDBNull;
            }
        }
        public string UpColumnName
        {
            get
            {
                return string.Format("{0}{1}", this.ColumnName[0].ToString().ToUpper(), this.ColumnName.Substring(1));
            }
        }
        public string LowerColumnName
        {
            get
            {
                return string.Format("{0}{1}", this.ColumnName[0].ToString().ToLower(), this.ColumnName.Substring(1));
            }
        }
    }
}
Table

自定义T4

<#@ template language="C#" debug="false" hostspecific="false"#>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ assembly name="$(TargetDir)Biz.Framework.DataFactory.dll" #>
<#@ import namespace="Biz.Framework.DataFactory" #>
<#@ output extension=".cs"#>
using Biz.Framework.EntityLibrary;

namespace Biz.Framework.DataAccess
{
<# 
    var dbSchema = DBSchemaFactory.GetDBSchema();
    List<string> tableList = dbSchema.GetTablesList();
    foreach(string tableName in tableList)
    { #>
    public partial class <#=            tableName#>DAL: BaseDAL<<#=            tableName#>>
    {
    }
<#    } #>
}
DAL层的T4
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ assembly name="$(TargetDir)Biz.Framework.DataFactory.dll" #>
<#@ import namespace="Biz.Framework.DataFactory" #>
<#@ output extension=".cs" #>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Biz.Framework.EntityLibrary;
using Biz.Framework.DataAccess;

namespace Biz.Framework.BusinessLogic
{
<# 
    var dbSchema = DBSchemaFactory.GetDBSchema();
    List<string> tableList = dbSchema.GetTablesList();
    foreach(string tableName in tableList)
    { #>
    public partial class <#=tableName#>BLL: BaseBLL<<#=tableName#>>
    {
        public override void SetDAL()
        {
            dal = new <#=tableName#>DAL();
        }
    }
<#    } #>
}
BLL层的T4

T4的调试和生成