zoukankan      html  css  js  c++  java
  • 安装codesmith以及创建模板

    安装参考:https://www.cnblogs.com/xcsn/p/4529569.html

    代码步骤:

    1.批量生成模板BatchTest.cst

    <%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Description="NetTiers main template." Debug="True" ResponseEncoding="UTF-8"%>
    
    <%-- 注册实体层Entity模板 --%>
    <%@ Register Name="EntityTemplate" Template="Model.cst" MergeProperties="Flase" ExcludeProperties=""%>
     
    <%-- 添加引用 --%>
    <%@ Import Namespace="System.Collections.Generic" %>
    <%@ Import Namespace="System.Linq" %>
    
    <%-- 添加引用dll --%> <%@ Assembly Name="SchemaExplorer.SqlSchemaProvider" %> <script runat="template"> public string OutputDirectory=""; </script> <script runat="template"> //生成实体Entity类 private void GenerateEntityClasses() { try { //设置访问数据库地址 var SourceDatabase=new DatabaseSchema(); SourceDatabase.Provider=new SchemaExplorer.SqlSchemaProvider(); SourceDatabase.ConnectionString="Server=.;Initial Catalog=AAA;MultipleActiveResultSets=True;Max Pool Size=512;User Id=sa;Password=123456;"; OutputDirectory =Environment.CurrentDirectory+"\"+"models\";//输出文件夹 var mynamespace="WQB.Infrastructure.Data.Entity.DTO";//命名空间 //表名 var tables="TianBaoCallBack,TianbaoSynOrder"; var dictables=tables.ToLower().Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries).ToList(); CodeTemplate Template =new EntityTemplate(); foreach(TableSchema table in SourceDatabase.Tables) { if (dictables.Contains( table.Name.ToLower())==false){ continue; } Debug.WriteLine(table.Name); string FileDirectory = OutputDirectory +"\"+ table.Name +".cs"; //生成模板 Template.SetProperty("SourceTable",table); Template.SetProperty("Namespace",mynamespace); //文件输出 Template.RenderToFile(FileDirectory,true); Debug.WriteLine(FileDirectory +" 创建成功."); } // System.Diagnostics.Process.Start("explorer.exe", OutputDirectory); } catch(Exception e) {} } </script> <% //创建实体层Entity类 this.GenerateEntityClasses(); Debug.WriteLine("OK"); %> <%--输出提示--%> 生成成功!输出路径:<% Response.Write(OutputDirectory); %>

    2.生成模板样例Model.cst

    <%-- 
    Name: Database Table Properties
    Author: lwx
    Description: Create a list of properties from a database table
    --%>
    <%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Description="Create a list of properties from database table." %>
    <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="Table that the object is based on." %>
    <%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
    <%@ Property Name="Namespace" Type="String" Category="Context" Description="Table that the object is based on." %>
    <%@ Assembly Name="SchemaExplorer" %>
    <%@ Assembly Name="System.Data" %>
    <%@ Import Namespace="SchemaExplorer" %>
    <%@ Import Namespace="System.Data" %>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using WQB.Infrastructure.Core;
    using Chloe.Entity;
    
    namespace <%=Namespace  %>
    {
        /// <summary>
        /// 实体类:<%= GetClassName(SourceTable) %>/// </summary>
        [Table("<%= GetClassName(SourceTable) %>")]
        [Serializable]
        public class <%= GetClassName(SourceTable) %>_M
        {
            <% foreach (ColumnSchema column in SourceTable.Columns) { %>
            <% string dataType = GetCSharpVariableType(column);string lowerDataType=dataType.ToLower();%>
             <% string defaultVal="="";"; %>
            <% if (column.IsPrimaryKeyMember) {%>
            <% if (column.ExtendedProperties["CS_Default"].Value==""){ %>
            protected <%= GetPrimaryKeyType(SourceTable) %>  <%=GetMemberVariableName(column) %>;
            <%} else {%>
            protected <%= GetPrimaryKeyType(SourceTable) %>  <%=GetMemberVariableName(column) %>=<%=column.ExtendedProperties["CS_Default"].Value%>;
            <% } %>
            <%} else {%>        
            <% if (column.ExtendedProperties["CS_Default"].Value.ToString().TrimStart(new char[1]{'('}).TrimEnd(new char[1]{')'})=="''"){ %>
            <%if(lowerDataType=="string") defaultVal = "="";";  %>
            <%else if(lowerDataType.Contains("guid")) defaultVal = @"=Guid.NewGuid();"; %>
            <%else if(lowerDataType.Contains("datetime")) defaultVal = @";"; %>
            <%else if(lowerDataType.Contains("datetime")) defaultVal = @";"; %>       
            <%else defaultVal = @"="""";"; %>
            protected <%= GetCSharpVariableType(column)%> <%=GetMemberVariableName(column) %> <%=defaultVal%>
            <%} else if  (column.ExtendedProperties["CS_Default"].Value.ToString().TrimStart(new char[1]{'('}).TrimStart(new char[1]{'('}).TrimEnd(new char[1]{')'}).TrimEnd(new char[1]{')'})=="0"){%>
            <%if(lowerDataType=="string") defaultVal = @"=""0"";";  %>
            <%else if(lowerDataType.Contains("bool")) defaultVal = @"=false;"; %>
            <%else defaultVal=@"=0;"; %>
            protected <%= GetCSharpVariableType(column) %> <%=GetMemberVariableName(column) %> <%=defaultVal%>
            <%} else if  (column.ExtendedProperties["CS_Default"].Value.ToString().TrimStart(new char[1]{'('}).TrimStart(new char[1]{'('}).TrimEnd(new char[1]{')'}).TrimEnd(new char[1]{')'})=="1"){%>
            <%if(lowerDataType=="string") defaultVal = @"=""1"";";  %>
            <%else if(lowerDataType.Contains("bool")) defaultVal = @"=true;"; %>
            <%else defaultVal = @"=1;"; %>
            protected <%= GetCSharpVariableType(column) %> <%=GetMemberVariableName(column) %> <%=defaultVal%>
            <%} else if  (column.ExtendedProperties["CS_Default"].Value.ToString().TrimStart(new char[1]{'('}).TrimStart(new char[1]{'('}).TrimEnd(new char[1]{')'}).TrimEnd(new char[1]{')'})=="2"){%>
            <%if(lowerDataType=="string") defaultVal = @"=""2"";"; %>
            <%else defaultVal = @"=2;"; %>
            protected <%= GetCSharpVariableType(column) %> <%=GetMemberVariableName(column) %> <%=defaultVal%>
            <%} else if  (column.ExtendedProperties["CS_Default"].Value.ToString().TrimStart(new char[1]{'('}).TrimEnd(new char[1]{')'}).TrimEnd(new char[1]{')'}).TrimEnd(new char[1]{'('})=="getdate"){%>
              <%if(lowerDataType=="string") defaultVal = @"=DateTime.Now.ToString(""yyyy-MM-dd HH:mm:ss"");"; %>
            <%else defaultVal = @"=DateTime.Now;"; %>
            protected <%= GetCSharpVariableType(column) %><%if (lowerDataType=="datetime"&&column.Name.ToLower()!="addtime"&&column.Name.ToLower()!="modifytime"&&column.Name.ToLower()!="updatetime"){%>?<%}%>  <%=GetMemberVariableName(column) %><%if (defaultVal=="="";")%>;<%else%><%=defaultVal%>
             <%} else if  (column.ExtendedProperties["CS_Default"].Value.ToString().TrimStart(new char[1]{'('}).TrimEnd(new char[1]{')'}).TrimEnd(new char[1]{')'}).TrimEnd(new char[1]{'('})=="newid"){%>
              <%if(lowerDataType=="string") defaultVal = @"=Guid.NewGuid().ToString();"; %>
            <%else defaultVal = @"=Guid.NewGuid();"; %>
            protected <%= GetCSharpVariableType(column) %>  <%=GetMemberVariableName(column) %><%if (defaultVal=="="";")%>;<%else%><%=defaultVal%>
            <%} else {%>
            <% if (column.ExtendedProperties["CS_Default"].Value==""){ %>      
            <%switch(lowerDataType){ %>
            <% case "string":%>
            <% defaultVal = @"="""";"; %>
            <% break;%>
            <% case "datetime":%>
            <% if (column.Name.ToLower()=="addtime"||column.Name.ToLower()=="modifytime"||column.Name.ToLower()=="updatetime") {%>
            <% defaultVal = "=DateTime.Now;"; %>
            <%}%>
            <%else{%>            
            <%}%>
            <% break;%>
             <% case "short":%>
             <% case "short?":%>
             <% defaultVal = "=0;"; %>
             <% break;%>
             <% case "int":%>
             <% case "int?":%>
             <% defaultVal = "=0;"; %>
             <% break;%>
             <% case "long":%>
             <% case "long?":%>
             <% defaultVal = "=0;"; %>
             <% break;%>
             <% case "float":%>
             <% case "float?":%>
             <% defaultVal = "=0f;"; %>
             <% break;%>
             <% case "decimal":%>
             <% case "decimal?":%>
             <% defaultVal = "=0M;"; %>
             <% break;%>
             <% case "bool":%>
             <% case "bool?":%>
             <% defaultVal = "=false;"; %>
             <% break;%>
             <% case "byte":%>
             <% case "byte?":%>
             <% defaultVal = "=0;"; %>
             <% break;%>
             <% case "single":%>
             <% case "single?":%>
             <% defaultVal = "=0;"; %>
             <% break;%>
             <% default:%>        
             <%break;%>
             <%}%>      
            protected <%= dataType %><%if (lowerDataType=="datetime"&&column.Name.ToLower()!="addtime"&&column.Name.ToLower()!="modifytime"&&column.Name.ToLower()!="updatetime"){%>?<%}%>  <%=GetMemberVariableName(column) %>=null;
                <% } %>   
                 <% else {%>
            protected <%= dataType %> <%=GetMemberVariableName(column) %><%if (defaultVal=="="";")%>;<%else%><%=column.ExtendedProperties["CS_Default"].Value%>
                 <% }} %>
            <% }} %>
            public <%= GetClassName(SourceTable) %>_M()
            {
            }    
            public <%= GetClassName(SourceTable) %>_M(<%= GetPrimaryKeyType(SourceTable) %> id)
            {
                <%=GetMemberVariableName(SourceTable.PrimaryKey.MemberColumns[0]) %>=id;
            }    
            <% for (int i = 0; i < SourceTable.Columns.Count; i++) { %>
            /// <summary>
            /// <%= SourceTable.Columns[i].Description %>
            /// </summary>
            <% if (SourceTable.Columns[i].IsPrimaryKeyMember) {%>
            [Column(IsPrimaryKey = true)]
            <%} %>
            <% if ((bool)SourceTable.Columns[i].ExtendedProperties["CS_IsIdentity"].Value) {%>
            [AutoIncrement]
            <%} %>
            public <%= GetCSharpVariableType(SourceTable.Columns[i]) %><%if (GetCSharpVariableType(SourceTable.Columns[i]).ToLower()=="datetime"&&SourceTable.Columns[i].Name.ToLower()!="addtime"&&SourceTable.Columns[i].Name.ToLower()!="modifytime"&&SourceTable.Columns[i].Name.ToLower()!="updatetime"){%>?<%}%> <%= GetPropertyName(SourceTable.Columns[i]) %>
            {
                get {return <%= GetMemberVariableName(SourceTable.Columns[i]) %>;}
                set {<%= GetMemberVariableName(SourceTable.Columns[i]) %> = value;}
            }        
            <% if (i < SourceTable.NonPrimaryKeyColumns.Count - 1) Response.Write("
    "); %>        
            <% } %>        
            public static <%= GetClassName(SourceTable) %>_M Get<%= GetClassName(SourceTable) %>(<%= GetPrimaryKeyType(SourceTable) %> id)
            {
                return new <%= GetClassName(SourceTable) %>_M(id);
            }
        }
    }
    <script runat="template">
    public string GetMemberVariableDeclarationStatement(ColumnSchema column)
    {
        return GetMemberVariableDeclarationStatement("protected", column);
    }
    
    public string GetMemberVariableDeclarationStatement(string protectionLevel, ColumnSchema column)
    {
        string statement ="protected ";
        if(column.IsForeignKeyMember)
        {
            statement+=column.Name.Substring(0,column.Name.Length-2)+" "+column.Name.Substring(0,column.Name.Length-2)+"Id"; 
        }
        else
        {
            statement += GetCSharpVariableType(column) + " " + GetMemberVariableName(column);
        }
        string defaultValue = GetMemberVariableDefaultValue(column);
        if (defaultValue != "")
        {
            statement += " = " + defaultValue;
        }
        
        statement += ";";
        
        return statement;
    }
    
    public string GetReaderAssignmentStatement(ColumnSchema column, int index)
    {
        string statement = "if (!reader.IsDBNull(" + index.ToString() + ")) ";
        statement += GetMemberVariableName(column) + " = ";
        
        if (column.Name.EndsWith("TypeCode")) statement += "(" + column.Name + ")";
        
        statement += "reader." + GetReaderMethod(column) + "(" + index.ToString() + ");";
        
        return statement;
    }
    
    public string GetCamelCaseName(string value)
    {
        return value.Substring(0, 1).ToLower() + value.Substring(1);
    }
    
    public string GetMemberVariableName(ColumnSchema column)
    {
        string propertyName = column.Name;
        //string memberVariableName =  GetCamelCaseName(propertyName);    
        //return memberVariableName;
        return "_"+propertyName.Substring(0,1).ToLower()+propertyName.Substring(1,propertyName.Length-1);
        
    }
    
    public string GetPropertyName(ColumnSchema column)
    {
        string propertyName = column.Name;
        
        //if (propertyName == column.Table.Name + "Name") return "Name";
        //if (propertyName == column.Table.Name + "Description") return "Description";
        
        //if (propertyName.EndsWith("TypeCode"))
        //propertyName =propertyName.Substring(0, propertyName.Length - 4).ToUpper();//propertyName.Substring(0,1).ToUpper()+propertyName.Substring(1,propertyName.Length);  // 
        
        //return propertyName.Substring(0,1).ToUpper()+propertyName.Substring(1,propertyName.Length-1).ToLower();
        return propertyName;
        
    }
            
    public string GetMemberVariableDefaultValue(ColumnSchema column)
    {
        switch (column.DataType)
        {
            case DbType.Guid:
            {
                return "Guid.Empty";
            }
            case DbType.AnsiString:
            case DbType.AnsiStringFixedLength:
            case DbType.String:
            case DbType.StringFixedLength:
            {
                return "String.Empty";
            }
            default:
            {
                return "";
            }
        }
    }
    
    public string GetCSharpVariableType(ColumnSchema column)
    {
        if (column.Name.EndsWith("TypeCode")) return column.Name;
        
        switch (column.DataType)
        {
            case DbType.AnsiString: return "string";
            case DbType.AnsiStringFixedLength: return "string";
            case DbType.Binary: return "byte[]";
            case DbType.Boolean: return "bool";
            case DbType.Byte: return "byte";
            case DbType.Currency: return "decimal";
            case DbType.Date: return "DateTime";
            case DbType.DateTime: return "DateTime";
            case DbType.Decimal: return "decimal";
            case DbType.Double: return "double";
            case DbType.Guid: return "Guid";
            case DbType.Int16: return "short";
            case DbType.Int32: return "int";
            case DbType.Int64: return "long";
            case DbType.Object: return "object";
            case DbType.SByte: return "sbyte";
            case DbType.Single: return "float";
            case DbType.String: return "string";
            case DbType.StringFixedLength: return "string";
            case DbType.Time: return "TimeSpan";
            case DbType.UInt16: return "ushort";
            case DbType.UInt32: return "uint";
            case DbType.UInt64: return "ulong";
            case DbType.VarNumeric: return "decimal";
            default:
            {
                return "__UNKNOWN__" + column.NativeType;
            }
        }
    }
    
    public string GetReaderMethod(ColumnSchema column)
    {
        switch (column.DataType)
        {
            case DbType.Byte:
            {
                return "GetByte";
            }
            case DbType.Int16:
            {
                return "GetInt16";
            }
            case DbType.Int32:
            {
                return "GetInt32";
            }
            case DbType.Int64:
            {
                return "GetInt64";
            }
            case DbType.AnsiStringFixedLength:
            case DbType.AnsiString:
            case DbType.String:
            case DbType.StringFixedLength:
            {
                return "GetString";
            }
            case DbType.Boolean:
            {
                return "GetBoolean";
            }
            case DbType.Guid:
            {
                return "GetGuid";
            }
            case DbType.Currency:
            case DbType.Decimal:
            {
                return "GetDecimal";
            }
            case DbType.DateTime:
            case DbType.Date:
            {
                return "GetDateTime";
            }
            case DbType.Binary:
            {
                return "GetBytes";
            }
            default:
            {
                return "__SQL__" + column.DataType;
            }
        }
    }
    
    public string GetClassName(TableSchema table)
    {
        return table.Name;
    }
    
    public string GetSqlDbType(ColumnSchema column)
    {
        switch (column.NativeType)
        {
            case "bigint": return "BigInt";
            case "binary": return "Binary";
            case "bit": return "Bit";
            case "char": return "Char";
            case "datetime": return "DateTime";
            case "decimal": return "Decimal";
            case "float": return "Float";
            case "image": return "Image";
            case "int": return "Int";
            case "money": return "Money";
            case "nchar": return "NChar";
            case "ntext": return "NText";
            case "numeric": return "Decimal";
            case "nvarchar": return "NVarChar";
            case "real": return "Real";
            case "smalldatetime": return "SmallDateTime";
            case "smallint": return "SmallInt";
            case "smallmoney": return "SmallMoney";
            case "sql_variant": return "Variant";
            case "sysname": return "NChar";
            case "text": return "Text";
            case "timestamp": return "Timestamp";
            case "tinyint": return "TinyInt";
            case "uniqueidentifier": return "UniqueIdentifier";
            case "varbinary": return "VarBinary";
            case "varchar": return "VarChar";
            default: return "__UNKNOWN__" + column.NativeType;
        }
    }
    
    public string GetPrimaryKeyType(TableSchema table)
    {
        if (table.PrimaryKey != null)
        {
            return GetCSharpVariableType(table.PrimaryKey.MemberColumns[0]);
            
        }
        else
        {
            throw new ApplicationException("This template will only work on tables with a primary key.");
        }
    }
    
    public override string GetFileName()
    {
        return this.GetClassName(this.SourceTable) + ".cs";
    }
    
    public string GetMemberVariableDefaultValue2(ColumnSchema column)
    {
        switch (column.DataType)
        {
            case DbType.Guid:
            {
                return "Guid.Empty";
            }
            case DbType.AnsiString:
            case DbType.AnsiStringFixedLength:
            case DbType.String:
            case DbType.StringFixedLength:
            {
                return "String.Empty";
            }
            default:
            {
                return "";
            }
        }
    }
    </script>
  • 相关阅读:
    macOS 在终端中使用 adb命令,每次都要source ~/.bash_profile 才生效
    判断一个数是奇数还是偶数?
    使用SQL Server 扩展事件来创建死锁的跟踪
    sql server阻塞(block)处理
    sqlserver的CTE实现递归查询
    sqlserver 行转列
    sqlserver字符串多行合并为一行
    git alias 配置别名,让命令更简洁,提高效率
    vim 快捷键
    Git bash 命令行中的快捷键
  • 原文地址:https://www.cnblogs.com/a735882640/p/8397745.html
Copyright © 2011-2022 走看看