.net core 用T4模板连接MySql生成实体类

1 篇文章 0 订阅
1 篇文章 0 订阅

author:靓仔建

联系方式:qq(1337489969) 微信(gaolian1025)

.net core 用T4模板连接MySql生成实体类标题

 4,把MySql.Data.dll放在项目根目录,也可以自行更改。

    在之前参考那个博友的文章,他的是连接SQL server的。

下面是参考他的T4模板,进行了修改的:

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=""  #>

<#@ assembly name="System.Data" #>
<#@ assembly name="$(ProjectDir)MySql.Data.dll" #>     //MySql.Data.dll需放在项目根目录也可以自行更改
<#@ import namespace="MySql.Data.MySqlClient" #>
<#@ import namespace="MySql.Data" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating"#>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="System" #>
<#@ assembly name="EnvDTE90" #>
<#@ import namespace="EnvDTE90" #>

<#          
            //    声明字段
            MySqlConnection conn;
            string sql;
            MySqlCommand command;
            MySqlDataReader reader;
            List<string> tablesName;
            List<string> tablesMark;
            MySqlDataReader markReader;        //用来读取字段注释的Reader
            string templateFileDir = Path.GetDirectoryName(Host.TemplateFile); //获取tt模板目录
            //    数据库连接
            string strConn = "Server=localhost;Database=tianya;User=root;Password=root;charset=utf8;";        //数据库连接字符串-这个换了环境就要改
            conn = new MySqlConnection(strConn);
            conn.Open();
            //    查MySql数据库中有多少张表的sql语句
            sql = "show table status";
            command = new MySqlCommand(sql, conn);
            reader = command.ExecuteReader();
            tablesName = new List<string>();
            tablesMark = new List<string>();
            //    把表集合赋值到tablesName
            while (reader.Read())
            {
                tablesName.Add(reader[0].ToString());        //获取表名称
                tablesMark.Add(reader[17].ToString());        //获取表注释
            }
            reader.Close();

            //    获取Visual Studio实例
            EnvDTE.DTE dte = (EnvDTE.DTE)
          ((IServiceProvider)Host).GetService(typeof(EnvDTE.DTE));
            EnvDTE.ProjectItem templateProjectItem = 
          dte.Solution.FindProjectItem(Host.TemplateFile);
            
            //    循环映射模型文件
            for (int i =0; i < tablesName.Count ; i++)
            {
                List<string> columsName = new List<string>();
                List<Type> columsType = new List<Type>();
                //    获取数据库表的字段的名称
                sql = string.Format("SHOW COLUMNS FROM {0}", tablesName[i]);
                command.CommandText = sql;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    columsName.Add(reader.GetString(0));
                }
                reader.Close();
                //    获取数据库表的字段的类型
                sql = string.Format("SELECT * FROM {0} LIMIT 0", tablesName[i]);
                command.CommandText = sql;
                reader = command.ExecuteReader();
                reader.Read();
                for(int z = 0 ; z < reader.FieldCount ; z++){
                    Type type =reader.GetFieldType(z);
                    columsType.Add(type);
                }
                reader.Close();
                #>
//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由T4模板自动生成
//       生成时间 <#= DateTime.Now #> 
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;

/// <summary>
/// <#= tablesMark[i] #>
/// </summary>
public class <#= tablesName[i] #>{

<#                //    获取字段的注释
                for(int j = 0; j<columsName.Count ; j++){ 
                    sql = string.Format("show full fields from {0} where Field = '{1}'" ,
                 tablesName[i] , columsName[j].ToString());
                    command.CommandText = sql;
                    markReader = command.ExecuteReader();
                    markReader.Read();
                #>
    /// <summary>
    /// <#= markReader[8].ToString() #>
    /// </summary>
    public <#= columsType[j] #>  <#= columsName[j] #> { get; set;}
<#                markReader.Close();
                } #>
}
                <# 
                byte[] byData = new byte[100];
                char[] charData = new char[1000];
                //    此地址与T4模板同目录
                string path = templateFileDir +"\\"+tablesName[i]+".cs";
                try
                {
                    //    将生成的文件添加到T4模板下关联
                    File.WriteAllText(path , this.GenerationEnvironment.ToString());
                    templateProjectItem.ProjectItems.AddFromFile(path);
                }
                catch (IOException e)
                {
                    Console.WriteLine(e.ToString());
                }
                this.GenerationEnvironment.Clear();
            //↑↑清空T4模板当前的 文本模板转换进程(T4)用于组合生成的文本输出的字符串↑↑
            } 

            command.Dispose();
            conn.Close();
        #>
        
        
        <#= "此文件为固定生成的文件,不必理会。" #>

该文为原创文章,转载请注明原文出处

Author:靓仔建 w: gaolian1025

(希望能帮助到各位,大家的支持是我创作最大动力!现在待业中,希望大家能推荐一下工作。(专注.net C# 6年))

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值