CodeSmith单表生成实体模板与生成多表实体模板

 生成单实体模板:

<%@ Template Language="C#" TargetLanguage="C#" %>
<%@ Assembly Name="SchemaExplorer"%>
<%@ Import Namespace="SchemaExplorer"%>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema"%>

using System;
using System.Collections.Generic;
namespace Model
{
    public class <%=GetClassName()%>Entity
    {
    <%foreach(ColumnSchema column in this.SourceTable.Columns)%>
    <%{%>   
        /// <summary>        
        ///<%=column.Description%>
        /// </summary>
        public <%=GetCSDataType(column)%><%=column.AllowDBNull&&GetCSDataType(column)!="string"?"?":""%> <%=ToPascal(column.Name)%>{get;set;}
<%}%> } } <script runat="template"> //Pascal命名法(将首字母大写) public string ToPascal(string s) { return s.Substring(0,1).ToUpper()+s.Substring(1); } //骆驼命名法(将首字母小写) public string ToCamel(string s) { return s.Substring(0,1).ToLower()+s.Substring(1); } //得到类的名字(由表名而来) public string GetClassName() { string s=this.SourceTable.Name;//取到表名 //判断表名是不是以S结尾,如果是去掉S if (s.EndsWith("s")) { return ToPascal(s.Substring(0,s.Length-1)); } return ToPascal(s); } //得到C#的数据类型(将基本常用的数据类型意逐个转换) public static string GetCSDataType(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 override string GetFileName() { return this.GetClassName()+".cs"; } </script>

 生成多表实体模板:

MultipleTemplate.cst

<%@ CodeTemplate Language="C#" TargetLanguage="Text" Src="" Inherits="" Debug="False" Description="Template description here." %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer"%>
<%-- 数据库 --%>
<%@ Property Name="SourceDatabase" type="SchemaExplorer.DatabaseSchema" DeepLoad="True" Optional="False" Category="01. GettingStarted - Required" Description="Database that the tables views, and storedprocedures should be based on. IMPORTANT!!! If SourceTables and SourceViews areleft blank, the Entire Database will then be generated." %>
<%-- 注册实体层Entity模板 --%>
<%@ Register Name="EntityTemplate" Template="Entity.cst" MergeProperties="Flase" ExcludeProperties=""%>

<script runat="template">
    //解决方案输出路径
    private string Directory = String.Empty;
    [Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
    [Optional, NotChecked]
    [DefaultValue("")]
    public string OutputDirectory
    {
        get
        {
            return Directory;
        }
        set
        {
            if (value.EndsWith(@"\"))
                value = value.Substring(0, value.Length - 1);
            Directory = value;
        }
    }
</script>

<script runat="template">
private void GenerateEntityClasses()
{
    Debug.WriteLine("----------------------实体Entity类 生成Start----------------------");
    CodeTemplate Template = new EntityTemplate();
    foreach(TableSchema table in this.SourceDatabase.Tables)
    {
        //string filedirectory = outputdirectory +@"\" + table.name + ".cs";
        string FileDirectory = this.GetFileDirectory("Model",table.Name,"");  //创建Model子文件夹
        Template.SetProperty("Table",table);
        //文件输出
        Template.RenderToFile(FileDirectory,true);
        Debug.WriteLine(FileDirectory +" 创建成功.");
    }
    Debug.WriteLine("----------------------实体Entity类 生成End----------------------");
}
    //将字符串首字母转换为大写  
    private string MakeCamel(string value)
    {
        return value.Substring(0, 1).ToUpper() + value.Substring(1);
    }
    
    private string GetFileDirectory(string flolderName,string tabName,string surfix)
    {
        return string.Format("{0}\\{1}\\{2}{3}.cs",OutputDirectory,flolderName,MakeCamel(tabName),surfix);
    }
</script>
<%
this.GenerateEntityClasses();
Debug.WriteLine("OK");
%>

 

Entity.cst

<%@ CodeTemplate Language="C#" Inherits="CodeTemplate" TargetLanguage="Text" Description="NetTiers main template." Debug="True" ResponseEncoding="UTF-8"%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>

<%@ Property Name="Table" type="TableSchema" DeepLoad="True" Optional="False" Category="01. Getting Started - Required"Description="Database that the tables views, and stored procedures shouldbe based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, theEntire Database will then be generated." %>
<script runat="template">
    //Pascal命名法(将首字母大写)
    public string ToPascal(string s)
    {
        return s.Substring(0,1).ToUpper()+s.Substring(1);
    }
    //骆驼命名法(将首字母小写)
    public string ToCamel(string s)
    {
        return s.Substring(0,1).ToLower()+s.Substring(1);
    }
    //得到类的名字(由表名而来)
    public string GetClassName()
    {
        string s=this.Table.Name;//取到表名
        //判断表名是不是以S结尾,如果是去掉S
        if (s.EndsWith("s"))
        {
             return ToPascal(s.Substring(0,s.Length-1));
        }
        return ToPascal(s);
    }
    public string DataType2CSharpType(System.Data.DbType dbType)
    {
        switch (dbType)
        {
            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.DateTime2:return "DateTime";
            case DbType.DateTimeOffset: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 "DateTime";
            case DbType.UInt16: return "ushort";
            case DbType.UInt32:return "uint";
            case DbType.UInt64:return "ulong";
            case DbType.VarNumeric:return "decimal";
            case DbType.Xml:return "string";
            default:return "object";
        }
    }
</script>
using System;
using System.Collections.Generic;
using System.Text;
namespace Entity
{
    public class <%=GetClassName()%>Entity
    {
    <% foreach(ColumnSchema col in Table.Columns)
        { %>
            /// <summary>        
            ///<%=col.Description%>
            /// </summary>
            public <%= DataType2CSharpType(col.DataType) %> <%=ToPascal(col.Name) %>{ get;set; }
     <% } %>
     }
 }

 很久不用,再用发现不会连接数据库了,又查了下:

编译过后会在属性窗口出现可以设置的属性

 

 

 

SourceTable属性默认为空, 点击右侧的那个三个点按钮,会弹出对话框

 

点击Data Source右侧的那个两个点按钮

 

 

 

点Add按钮新增一个数据库连接

 

输入Name,Provider Type选择SqlSchemaProvider,点击Connection String 右侧的三点按钮

 

 

 

 

 

 

 

输入Server Name,可以选择Windows身份认证或者SQL Server 密码认证,然后选择一个数据库,最后点击OK,接着再点OK,回到选择表界面,下拉框中选择刚加入的数据库,会自动列出该库中的所有表

 

2、设置SourceTable
先执行
Tools-Build
然后在属性杂项一栏中设置SourceTable
选择数据库,再选择表。

 

Tools  ->generate  生成表实体

public <%=GetCSDataType(column)%><%=column.AllowDBNull&&GetCSDataType(column)!="string"?"?":""%> <%=ToPascal(column.Name)%>{get;set;}


mysql连接串:
Server=10.0.1.20;Port=3308;Database=nongchanpinsuyuan_richdata;Uid=root;password=123456;charset=utf8mb4;Allow User Variables=True

sql server连接串:
Data Source=121.41.30.23;Initial Catalog=DEBeiKangAiZX_richdata;Persist Security Info=True;User ID=siia;Password=!CY@315_SiiaYjuw2





posted @ 2017-04-16 20:09  BloggerSb  阅读(518)  评论(0编辑  收藏  举报