T4模板使用记录,生成Model、Service、Repository

 

自己目前在搭建一个.NET Core的框架,本来是打算使用前端做代码生成器直接生成到文件的,快做好了。感觉好像使用T4更方便一些,所以也就有了这篇文章~ 

我还是有个问题没解决,就是我想生成每个类(接口)单独的文件~,如果有老师知道指点下啊~

在网上找了一篇相关文章 本文也是基于这个做了一下自己的修改。

首先公共程序集创建一个DbHelper.ttinclude

主要就是链接数据库,搜索数据库表及表中字段的信息。

你可以得到这样的结果:瞬间明了了,然后就  爱的魔力转圈圈~ 循环就好了!

代码是这样的:

<#+
    public class config
    {
        public static readonly string ConnectionString="Data Source=(local);Integrated Security=true;Initial Catalog=LJDAPP;";
        public static readonly string DbDatabase="LJDAPP"; 
    }
    public class DbHelper
    { 
        
        public static List GetDbTables(string connectionString, string database)
        { 
            string sql = string.Format(@"SELECT
                obj.name tablename,
                schem.name schemname,
                ISNULL(g.value,'') [description],
                idx.rows,
                CAST
                (
                CASE 
                WHEN (SELECT COUNT(1) FROM sys.indexes WHERE object_id= obj.OBJECT_ID AND is_primary_key=1) >=1 THEN 1
                ELSE 0
                END 
                AS BIT) HasPrimaryKey                                         
                from {0}.sys.objects obj 
                inner join {0}.dbo.sysindexes idx on obj.object_id=idx.id and idx.indid<=1
                INNER JOIN {0}.sys.schemas schem ON obj.schema_id=schem.schema_id
                left join {0}.sys.extended_properties g ON (obj.object_id = g.major_id AND g.minor_id = 0 AND g.name= 'MS_Description')
                where type='U' 
                order by obj.name", database); 
            DataTable dt = GetDataTable(connectionString, sql);
            return dt.Rows.Cast().Select(row => new DbTable
                {
                    TableName = row.Field<string>("tablename"),
                    SchemaName = row.Field<string>("schemname"),
                    Description=row.Field<string>("description"),
                    Rows = row.Field<int>("rows"),
                    HasPrimaryKey = row.Field<bool>("HasPrimaryKey")
                    }).ToList();
        }
        
 
        
        public static List GetDbColumns(string connectionString, string database, string tableName, string schema = "dbo")
        { 
            string sql = string.Format(@"
                WITH indexCTE AS
                (
                SELECT 
                ic.column_id,
                ic.index_column_id,
                ic.object_id    
                FROM {0}.sys.indexes idx
                INNER JOIN {0}.sys.index_columns ic ON idx.index_id = ic.index_id AND idx.object_id = ic.object_id
                WHERE  idx.object_id =OBJECT_ID(@tableName) AND idx.is_primary_key=1
                )
                select
                colm.column_id ColumnID,
                CAST(CASE WHEN indexCTE.column_id IS NULL THEN 0 ELSE 1 END AS BIT) IsPrimaryKey,
                colm.name ColumnName,
                systype.name ColumnType,
                colm.is_identity IsIdentity,
                colm.is_nullable IsNullable,
                cast(colm.max_length as int) ByteLength,
                (
                case 
                when systype.name='nvarchar' and colm.max_length>0 then colm.max_length/2 
                when systype.name='nchar' and colm.max_length>0 then colm.max_length/2
                when systype.name='ntext' and colm.max_length>0 then colm.max_length/2 
                else colm.max_length
                end
                ) CharLength,
                cast(colm.precision as int) Precision,
                cast(colm.scale as int) Scale,
                prop.value Remark
                from {0}.sys.columns colm
                inner join {0}.sys.types systype on colm.system_type_id=systype.system_type_id and colm.user_type_id=systype.user_type_id
                left join {0}.sys.extended_properties prop on colm.object_id=prop.major_id and colm.column_id=prop.minor_id
                LEFT JOIN indexCTE ON colm.column_id=indexCTE.column_id AND colm.object_id=indexCTE.object_id                                        
                where colm.object_id=OBJECT_ID(@tableName)
                order by colm.column_id", database);
            
            SqlParameter param = new SqlParameter("@tableName", SqlDbType.NVarChar, 100) { Value = string.Format("{0}.{1}.{2}", database, schema, tableName) };
            DataTable dt = GetDataTable(connectionString, sql, param);
            return dt.Rows.Cast().Select(row => new DbColumn()
                {
                    ColumnID = row.Field<int>("ColumnID"),
                    IsPrimaryKey = row.Field<bool>("IsPrimaryKey"),
                    ColumnName = row.Field<string>("ColumnName"),
                    ColumnType = row.Field<string>("ColumnType"),
                    IsIdentity = row.Field<bool>("IsIdentity"),
                    IsNullable = row.Field<bool>("IsNullable"),
                    ByteLength = row.Field<int>("ByteLength"),
                    CharLength = row.Field<int>("CharLength"),
                    Scale = row.Field<int>("Scale"),
                    Remark = row["Remark"].ToString()
                    }).ToList();
        }

             

 
        
        public static DataTable GetDataTable(string connectionString, string commandText, params SqlParameter[] parms)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = commandText;
                command.Parameters.AddRange(parms);
                SqlDataAdapter adapter = new SqlDataAdapter(command);

                DataTable dt = new DataTable();
                adapter.Fill(dt);

                return dt;
            }
        }

        
    }
 
    /// 
    /// 表结构
    /// 
    public sealed class DbTable
    {
        /// 
        /// 表名称
        /// 
        public string TableName { get; set; }
        /// 
        /// 表的架构
        /// 
        public string SchemaName { get; set; }
        /// 
        /// 表的说明
        /// 
        public string Description { get; set; }
        /// 
        /// 表的记录数
        /// 
        public int Rows { get; set; }

        /// 
        /// 是否含有主键
        /// 
        public bool HasPrimaryKey { get; set; }
    }
    
 
    /// 
    /// 表字段结构
    /// 
    public sealed class DbColumn
    {
        /// 
        /// 字段ID
        /// 
        public int ColumnID { get; set; }

        /// 
        /// 是否主键
        /// 
        public bool IsPrimaryKey { get; set; }

        /// 
        /// 字段名称
        /// 
        public string ColumnName { get; set; }

        /// 
        /// 字段类型
        /// 
        public string ColumnType { get; set; }

        /// 
        /// 数据库类型对应的C#类型
        /// 
        public string CSharpType
        {
            get
            {
                return SqlServerDbTypeMap.MapCsharpType(ColumnType);
            }
        }

        /// 
        /// 
        /// 
        public Type CommonType
        {
            get
            {
                return SqlServerDbTypeMap.MapCommonType(ColumnType);
            }
        }

        /// 
        /// 字节长度
        /// 
        public int ByteLength { get; set; }

        /// 
        /// 字符长度
        /// 
        public int CharLength { get; set; }

        /// 
        /// 小数位
        /// 
        public int Scale { get; set; }

        /// 
        /// 是否自增列
        /// 
        public bool IsIdentity { get; set; }

        /// 
        /// 是否允许空
        /// 
        public bool IsNullable { get; set; }

        /// 
        /// 描述
        /// 
        public string Remark { get; set; }
    }
    
 

    public class SqlServerDbTypeMap
    {
        public static string MapCsharpType(string dbtype)
        {
            if (string.IsNullOrEmpty(dbtype)) return dbtype;
            dbtype = dbtype.ToLower();
            string csharpType = "object";
            switch (dbtype)
            {
                case "bigint": csharpType = "long"; break;
                case "binary": csharpType = "byte[]"; break;
                case "bit": csharpType = "bool"; break;
                case "char": csharpType = "string"; break;
                case "date": csharpType = "DateTime"; break;
                case "datetime": csharpType = "DateTime"; break;
                case "datetime2": csharpType = "DateTime"; break;
                case "datetimeoffset": csharpType = "DateTimeOffset"; break;
                case "decimal": csharpType = "decimal"; break;
                case "float": csharpType = "double"; break;
                case "image": csharpType = "byte[]"; break;
                case "int": csharpType = "int"; break;
                case "money": csharpType = "decimal"; break;
                case "nchar": csharpType = "string"; break;
                case "ntext": csharpType = "string"; break;
                case "numeric": csharpType = "decimal"; break;
                case "nvarchar": csharpType = "string"; break;
                case "real": csharpType = "Single"; break;
                case "smalldatetime": csharpType = "DateTime"; break;
                case "smallint": csharpType = "short"; break;
                case "smallmoney": csharpType = "decimal"; break;
                case "sql_variant": csharpType = "object"; break;
                case "sysname": csharpType = "object"; break;
                case "text": csharpType = "string"; break;
                case "time": csharpType = "TimeSpan"; break;
                case "timestamp": csharpType = "byte[]"; break;
                case "tinyint": csharpType = "byte"; break;
                case "uniqueidentifier": csharpType = "Guid"; break;
                case "varbinary": csharpType = "byte[]"; break;
                case "varchar": csharpType = "string"; break;
                case "xml": csharpType = "string"; break;
                default: csharpType = "object"; break;
            }
            return csharpType;
        }
           
        public static Type MapCommonType(string dbtype)
        {
            if (string.IsNullOrEmpty(dbtype)) return Type.Missing.GetType();
            dbtype = dbtype.ToLower();
            Type commonType = typeof(object);
            switch (dbtype)
            {
                case "bigint": commonType = typeof(long); break;
                case "binary": commonType = typeof(byte[]); break;
                case "bit": commonType = typeof(bool); break;
                case "char": commonType = typeof(string); break;
                case "date": commonType = typeof(DateTime); break;
                case "datetime": commonType = typeof(DateTime); break;
                case "datetime2": commonType = typeof(DateTime); break;
                case "datetimeoffset": commonType = typeof(DateTimeOffset); break;
                case "decimal": commonType = typeof(decimal); break;
                case "float": commonType = typeof(double); break;
                case "image": commonType = typeof(byte[]); break;
                case "int": commonType = typeof(int); break;
                case "money": commonType = typeof(decimal); break;
                case "nchar": commonType = typeof(string); break;
                case "ntext": commonType = typeof(string); break;
                case "numeric": commonType = typeof(decimal); break;
                case "nvarchar": commonType = typeof(string); break;
                case "real": commonType = typeof(Single); break;
                case "smalldatetime": commonType = typeof(DateTime); break;
                case "smallint": commonType = typeof(short); break;
                case "smallmoney": commonType = typeof(decimal); break;
                case "sql_variant": commonType = typeof(object); break;
                case "sysname": commonType = typeof(object); break;
                case "text": commonType = typeof(string); break;
                case "time": commonType = typeof(TimeSpan); break;
                case "timestamp": commonType = typeof(byte[]); break;
                case "tinyint": commonType = typeof(byte); break;
                case "uniqueidentifier": commonType = typeof(Guid); break;
                case "varbinary": commonType = typeof(byte[]); break;
                case "varchar": commonType = typeof(string); break;
                case "xml": commonType = typeof(string); break;
                default: commonType = typeof(object); break;
            }
            return commonType;
        }
    }
    
    

#>
View Code

这个其实也是可以一起放到模板里的,不过因为好几个地方都需要用到,为了修改方便,还是单独拿出来比较好。

使用的时候会用到:

<#@ include file="$(ProjectDir)../LJD.App.Util/T4/DbHelper.ttinclude"  #>

显而易见,我放到了 LJD.App.Util类库下T4文件夹

这里说下T4 程序集指令  还有一篇文章:T4模版引擎之基础入门 是这样说的

<#@ assembly name="[assembly strong name|assembly file name]" #>

 

1、程序集指令相当于VS里面我们添加程序集引用的功能,该指令只有一个参数name,用以指定程序集名称,如果程序集已经在GAC里面注册,那么只需要写上程序集名称即可,如<#@ assembly name="System.Data.dll" #>,否则需要指定程序集的物理路径。

2、T4模版的程序集引用是完全独立的,也就是说我们在项目中引用了一些程序集,然后项目中添加了一个T4模版,T4模版所需要的所有程序集引用必须明确的在模版中使用程序集执行引用才可以。

3、T4模版自动加载以下程序集Microsoft.VisualStudio.TextTemplating.1*.dll、System.dll、WindowsBase.dll,如果用到了其它的程序集需要显示的使用程序集添加引用才可以

4、可以使用 $(variableName) 语法引用 Visual Studio 或 MSBuild 变量(如 $(SolutionDir)),以及使用 %VariableName% 来引用环境变量。介绍几个常用的$(variableName) 变量:

    $(SolutionDir):当前项目所在解决方案目录

    $(ProjectDir):当前项目所在目录

    $(TargetPath):当前项目编译输出文件绝对路径

    $(TargetDir):当前项目编译输出目录,即web项目的Bin目录,控制台、类库项目bin目录下的debug或release目录(取决于当前的编译模式)

    举个例子:比如我们在D盘根目录建立了一个控制台项目TestConsole,解决方案目录为D:\LzrabbitRabbit,项目目录为
    D:\LzrabbitRabbit\TestConsole,那么此时在Debug编译模式下
    $(SolutionDir)的值为D:\LzrabbitRabbit
    $(ProjectDir)的值为D:\LzrabbitRabbit\TestConsole
    $(TargetPath)值为D:\LzrabbitRabbit\TestConsole\bin\Debug\TestConsole.exe
    $(TargetDir)值为D:\LzrabbitRabbit\TestConsole\bin\Debug\

好了,准备工作都做完了,要创建T4模板了,这个还要图吗?

T4模板使用记录,生成Model、Service、Repository_第1张图片

然后贴上这段代码,在foreach中发挥你的想想吧!对了,要注意命名空间和using哈~

<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Data.DataSetExtensions" #>
<#@ assembly name="System.Xml" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ include file="$(ProjectDir)../LJD.App.Util/T4/DbHelper.ttinclude"  #>
//------------------------------------------------------------------------------
// 
//     此代码由T4模板自动生成
//     生成时间 <#=        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")#> by Jelly
//     对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。
// 
//------------------------------------------------------------------------------
using LJD.App.Model.DbModels;

namespace LJD.App.Repository.IRepository
{
 <#    foreach(DbTable table in DbHelper.GetDbTables(config.ConnectionString, config.DbDatabase)){#> 
<#        if(table.TableName!="Base") {#>
        /// 
        /// <#=table.Description#>
        ///         
        public partial interface I<#=table.TableName#>Repository : IBaseRepository<<#=table.TableName#>>
        {

        }
<#} #>
        <#     }#> 
}  

 

你可能感兴趣的:(T4模板使用记录,生成Model、Service、Repository)