• mysql t4模板_Model


    Model.tt

    <#@ template debug="false" hostspecific="true" language="C#" #>
    <#@ include file="$(ProjectDir)..T4entityHelper.ttinclude" #>
    // <copyright file="ApplyVehicleApproveController.cs" company="ZJCX">
    // Copyright (c) PlaceholderCompany. All rights reserved.
    // </copyright>

    namespace ZJCX.DGC.ApplyVehicle.Model
    {
    using System;
    <#
    var connectionString = @"server=;port=;uid=;password=;character set=utf8mb4;";
    var database = "dgcapplyvehicledb";
    var entities = EntityHelper.GetMysqlEntities(connectionString, database);
    foreach(Entity entity in entities)
    {
    #>
    /// <summary>
    /// <#= EntityHelper.ToCamel(entity.EntityName) #>Model
    /// </summary>
    public partial class <#= EntityHelper.ToCamel(entity.EntityName) #>Model
    {
    <#
    for(int i = 0; i < entity.Fields.Count; i++)
    {
    var fieldComment = entity.Fields[i].Comment;
    if(string.IsNullOrWhiteSpace(fieldComment)){
    fieldComment=entity.Fields[i].Name;
    }
    #>
    /// <summary>
    /// <#= fieldComment #>
    /// </summary>

    public <#= entity.Fields[i].Type #><#= entity.Fields[i].IsNull?"?":""#> <#= entity.Fields[i].Name #> { get; set; }
    <#
    }
    #>
    }

    <#
    }
    #>
    }

    entityHelper.ttinclude

    <#@ assembly name="System.Core"#>
    <#@ assembly name="System.Data"#>
    <#@ assembly name="$(ProjectDir)..T4MySql.Data.dll"#>
    <#@ import namespace="System" #>
    <#@ import namespace="System.Data" #>
    <#@ import namespace="System.Data.SqlClient" #>
    <#@ import namespace="System.Collections.Generic" #>
    <#@ import namespace="System.Linq" #>
    <#@ import namespace="MySql.Data.MySqlClient" #>
    <#+
    public class EntityHelper
    {
    #region sererver
    public static List<Entity> GetEntities(string connectionString)
    {
    var list = new List<Entity>();
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
    string sql = @"SELECT
    表名 = d.name,
    表说明 = case when a.colorder=1 then isnull(f.value,'') else '' end,
    字段序号 = a.colorder,
    字段名 = a.name,
    标识 = case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then 1 else 0 end,
    主键 = case when exists(SELECT 1 FROM sysobjects where xtype='PK' and parent_obj=a.id and name in (
    SELECT name FROM sysindexes WHERE indid in( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid))) then 1 else 0 end,
    类型 = b.name,
    占用字节数 = a.length,
    长度 = COLUMNPROPERTY(a.id,a.name,'PRECISION'),
    小数位数 = isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),
    允许空 = case when a.isnullable=1 then 1 else 0 end,
    默认值 = isnull(e.text,''),
    字段说明 = isnull(g.[value],'')
    from
    syscolumns a
    left join
    systypes b
    on
    a.xusertype=b.xusertype
    inner join
    sysobjects d
    on
    a.id=d.id and d.xtype='U' and d.name<>'dtproperties'
    left join
    syscomments e
    on
    a.cdefault=e.id
    left join
    sys.extended_properties g
    on
    a.id=G.major_id and a.colid=g.minor_id
    left join
    sys.extended_properties f
    on
    d.id=f.major_id and f.minor_id=0

    order by
    a.id,a.colorder";
    var command = new SqlCommand(sql, connection);

    try
    {
    connection.Open();
    var reader = command.ExecuteReader();
    while (reader.Read())
    {
    var table = reader["表名"].ToString();
    var entity = list.FirstOrDefault(x => x.EntityName == table);
    if (entity == null)
    {
    entity = new Entity(table);
    var field=new Field
    {
    Name = reader["字段名"].ToString(),
    Type = GetCLRType(reader["类型"].ToString()),
    IsPRI = Convert.ToBoolean(reader["主键"]),
    IsNull = Convert.ToBoolean(reader["允许空"]),
    Comment = reader["字段说明"].ToString()
    };
    if(field.Type=="string" || field.Type=="byte[]"){
    field.IsNull=false;
    }
    entity.Fields.Add(field);
    list.Add(entity);
    }
    else
    {
    var field=new Field
    {
    Name = reader["字段名"].ToString(),
    Type = GetCLRType(reader["类型"].ToString()),
    IsPRI = Convert.ToBoolean(reader["主键"]),
    IsNull = Convert.ToBoolean(reader["允许空"]),
    Comment = reader["字段说明"].ToString()
    };
    if(field.Type=="string" || field.Type=="byte[]"){
    field.IsNull=false;
    }
    entity.Fields.Add(field);
    }
    }
    reader.Close();
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.Message);
    }
    }

    return list;
    }
    public static string GetCLRType(string dbType,string cType="")
    {
    string sysType = "string";
    switch (dbType)
    {
    case "bigint":
    case "bit":
    sysType = "long";
    break;
    case "smallint":
    sysType = "short";
    break;
    case "int":
    sysType = "int";
    break;
    case "uniqueidentifier":
    sysType = "Guid";
    break;
    case "smalldatetime":
    case "datetime":
    case "datetime2":
    case "date":
    case "time":
    sysType = "DateTime";
    break;
    case "float":
    sysType = "float";
    break;
    case "double":
    sysType = "double";
    break;
    case "real":
    sysType = "float";
    break;
    case "numeric":
    case "smallmoney":
    case "decimal":
    case "money":
    sysType = "decimal";
    break;
    case "tinyint":
    if(cType=="tinyint(1)"){
    sysType = "bool";
    }
    else
    {
    sysType = "int";
    }
    break;
    case "image":
    case "binary":
    case "varbinary":
    case "timestamp":
    sysType = "DateTime";
    break;
    case "geography":
    sysType = "Microsoft.SqlServer.Types.SqlGeography";
    break;
    case "geometry":
    sysType = "Microsoft.SqlServer.Types.SqlGeometry";
    break;
    }
    return sysType;
    }
    #endregion

    #region mysql
    public static List<Entity> GetMysqlEntities(string connectionString, string database)
    {
    var list = new List<Entity>();
    var conn = new MySqlConnection(connectionString);
    try
    {
    conn.Open();
    var cmd = string.Format(@"SELECT `information_schema`.`COLUMNS`.`TABLE_SCHEMA`
    ,`information_schema`.`COLUMNS`.`TABLE_NAME`
    ,`information_schema`.`COLUMNS`.`COLUMN_NAME`
    ,`information_schema`.`COLUMNS`.`DATA_TYPE`
    ,`information_schema`.`COLUMNS`.`COLUMN_KEY`
    ,`information_schema`.`COLUMNS`.`COLUMN_TYPE`
    ,`information_schema`.`COLUMNS`.`IS_NULLABLE`
    ,`information_schema`.`COLUMNS`.`COLUMN_COMMENT`
    FROM `information_schema`.`COLUMNS`
    WHERE `information_schema`.`COLUMNS`.`TABLE_SCHEMA` = '{0}' ", database);
    using (var reader = MySqlHelper.ExecuteReader(conn, cmd))
    {
    while (reader.Read())
    {
    var table = reader["TABLE_NAME"].ToString();
    var column = reader["COLUMN_NAME"].ToString();
    var cType = reader["COLUMN_TYPE"].ToString();
    var type = GetCLRType(reader["DATA_TYPE"].ToString(),cType);
    var is_null = reader["IS_NULLABLE"].ToString() == "YES" ? true : false; //是否为空
    if (type == "string" || type == "byte[]") { is_null = false; }
    var is_pri = reader["COLUMN_KEY"].ToString() == "PRI" ? true : false; //是否为主键
    var comment = reader["COLUMN_COMMENT"].ToString();
    var entity = list.FirstOrDefault(x => x.EntityName == table);
    if (entity == null)
    {
    entity = new Entity(table);
    entity.Fields.Add(new Field
    {
    Name = column,
    Type = type,
    IsPRI = is_pri,
    IsNull = is_null,
    Comment = comment
    });

    list.Add(entity);
    }
    else
    {
    entity.Fields.Add(new Field
    {
    Name = column,
    IsPRI = is_pri,
    IsNull = is_null,
    Type = type,
    Comment = comment
    });
    }
    }
    }
    }
    finally
    {
    conn.Close();
    }

    return list;
    }

    #endregion

    public static string FirstCharToLower(string input)
    {
    if (String.IsNullOrEmpty(input))
    return input;
    string str = input.First().ToString().ToLower() + input.Substring(1);
    return str;
    }

    public static string ToCamel(string str){
    string[] wordArray = str.Split('_');
    string result="";
    foreach(var word in wordArray){
    result+=System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(word);
    }
    return result;
    }
    }

    public class Entity
    {
    public Entity()
    {
    this.Fields = new List<Field>();
    }

    public Entity(string name)
    : this()
    {
    this.EntityName = name;
    }

    public string EntityName { get; set; }
    public List<Field> Fields { get; set; }
    }
    public class Field
    {
    public string Name { get; set; }
    public string Type { get; set; }
    public bool IsPRI { get; set; }
    public bool IsNull { get; set; }
    public string Comment { get; set; }
    }
    #>

  • 相关阅读:
    算法
    什么叫「人的格局」?是否有必要培养大的格局或怎么培养?
    套接字
    信号量 P V测试详解
    Emacs快速入门
    Emacs 从入门到精通
    Linux多进程之间的文件锁
    mysql 登录报错:ERROR 1045 (28000)
    类职责协作模型
    .Netcore使用Session
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/12552425.html
Copyright © 2020-2023  润新知