CodeSmith模板

CodeSmith的模板默认是放在用户目录下的,在安装的时候可以自定义:

D:UsersadminDocumentsCodeSmith GeneratorTemplates

上次放在c盘电脑重装就没有了,好多模板都丢失了,于是又得重新写,为了方便就记到博客园里吧。

<%-- 
Name:
Author: mythsky
Created:<%=Datetime.Now.ToShortDateString() %>
Description: 
--%>
<%@ Template Language="C#" TargetLanguage="C#" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Text" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="数据库" %>
<%@ Property Name="NameSpace" Type="String" Description="命名空间" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using UCredit.Common.Mapping;

namespace <%=NameSpace %>
{
    [DataMapping(ObjectId = "<%=ConvertTablename2Pascal(SourceTable) %>")]
    [TableMapping(Name = "<%=SourceTable.Name %>")]
    public partial class <%=ConvertTablename2Pascal(SourceTable) %>
    {
    <%foreach(ColumnSchema col in SourceTable.Columns){ %>
        /// <summary>
        /// <%=col.Description %>
        /// </summary>
        <%if(col.NativeType=="timestamp"){ %>
        [FieldMapping(Power = PowerDmlEnum.None, FieldName = "last_time")]
        public <%=GetCSharpVariableType(col) %> <%=Convert2Pascal(col) %> {get;set;}
        <%}else { %>
        public <%=GetCSharpVariableType(col) %> <%=Convert2Pascal(col) %> {get;set;}
        <%} %>
    <%} %>
        public <%=ConvertTablename2Pascal(SourceTable) %>() { }
    }
}

<script runat="template">
    public string Convert2Pascal(ColumnSchema col)
    {
        StringBuilder sb = new StringBuilder();
        string[] strs = col.Name.Split(new char[] { '_'});
        foreach (string str in strs)
        {
            sb.Append(str.Substring(0,1).ToUpper());
            sb.Append(str.Substring(1));
        }
        return sb.ToString();
    }
    public string ConvertTablename2Pascal(TableSchema table)
    {
        StringBuilder sb = new StringBuilder();
        string[] strs = table.Name.Split(new char[] { '_'});
        int index=0;
        foreach (string str in strs)
        {
            if(index==0)
            {
                index++;
                continue;
            }
            sb.Append(str.Substring(0,1).ToUpper());
            sb.Append(str.Substring(1));
        }
        return sb.ToString();
    }
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 "short"; case DbType.UInt32: return "int"; case DbType.UInt64: return "long"; case DbType.VarNumeric: return "decimal"; default: { return "__UNKNOWN__" + column.NativeType; } } } </script>

 解决CodeSmith无法读取MySQL表注释和字段注释方法:

用附件中的SchemaExplorer.MySQLSchemaProvider.dll替换此目录中的:

Program Files (x86)CodeSmithv7.0SchemaProviders

附件地址:MySQLSchemaProvider.dll

CodeSmith 判断字段可空:

public string GetNullPreString(ColumnSchema column)
    {
        if(column.AllowDBNull&&column.SystemType.IsValueType)
            return "?";
        else
            return "";
    }

上面的代码可以作如下改造:

public <%=GetCSharpVariableType(col) %><%=GetNullPreString(col) %> <%=Convert2Pascal(col) %> {get;set;}

 其实上面转类型的方法在Codesmith的基本模板里是有的:

需要引入基本模板:

<%@ Assembly Name="Codesmith.BaseTemplates" %>
<%@ Import Namespace="CodeSmith.BaseTemplates" %>

然后就可以继承SqlCodeTemplate

<%@ Template Language="C#" TargetLanguage="C#" Inherits="SqlCodeTemplate" %>

之后就能调用GetCSharpVariableType方法了:

<%foreach(ColumnSchema col in SourceTable.Columns){ %>
        /// <summary>
        /// <%=col.Description %>
        /// </summary>
            public <%=GetCSharpVariableType(col) %> <%=col.Name %> {get;set;}
        <%} %>

API参考

方法参考

Model:

<%-- 
Name:
Author: maomao
Created:<%=Datetime.Now.ToShortDateString() %>
Description: 
--%>
<%@ Template Language="C#" TargetLanguage="C#" Inherits="SqlCodeTemplate" %>
<%@ Assembly Name="Codesmith.BaseTemplates" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="CodeSmith.BaseTemplates" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Text" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="数据库" %>
<%@ Property Name="NameSpace" Type="String" Description="命名空间" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace <%=NameSpace %>
{
    [Serializable]
    public partial class <%=ConvertTablename2Pascal(SourceTable) %>
    {
        #region 属性
        <%foreach(ColumnSchema col in SourceTable.Columns){ %>
        /// <summary>
        /// <%=col.Description %>
        /// </summary>
        public <%=GetCSharpVariableType(col) %> <%=col.Name %> {get;set;}
        <%} %>
        #endregion
        public <%=ConvertTablename2Pascal(SourceTable) %>() { }
        public <%=ConvertTablename2Pascal(SourceTable) %>(DataRow dr)
        {
        <%foreach(ColumnSchema col in SourceTable.Columns){ %>
            if(dr["<%=col.Name %>"]!=DBNull.Value)
            {
                this.<%=col.Name %>= (<%=GetCSharpVariableType(col) %>)dr["<%=col.Name %>"];
            }
        <%} %>
        }
    }
}
<script runat="template">
 public string Convert2Pascal(ColumnSchema col)
    {
        StringBuilder sb = new StringBuilder();
        string[] strs = col.Name.Split(new char[] { '_'});
        foreach (string str in strs)
        {
            sb.Append(str.Substring(0,1).ToUpper());
            sb.Append(str.Substring(1));
        }
        return sb.ToString();
    }
 public string ConvertTablename2Pascal(TableSchema table)
    {
        StringBuilder sb = new StringBuilder();
        string[] strs = table.Name.Split(new char[] { '_'});
        int index=0;
        foreach (string str in strs)
        {
//            if(index==0)
//            {
//                index++;
//                continue;
//            }
            sb.Append(str.Substring(0,1).ToUpper());
            sb.Append(str.Substring(1));
        }
        return sb.ToString();
    }
</script>
View Code

DAL:

<%-- 
Name:
Author: maomao
Created:<%=Datetime.Now.ToShortDateString() %>
Description: 
--%>
<%@ Template Language="C#" TargetLanguage="C#" Inherits="SqlCodeTemplate" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="CodeSmith.BaseTemplates" %>
<%@ Import Namespace="CodeSmith.BaseTemplates" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Text" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="数据库" %>
<%@ Property Name="NameSpace" Type="String" Description="命名空间" %>

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace <%=NameSpace %>
{
    public static partial class <%=SourceTable.Name %>DAL
    {
        public static List<<%=SourceTable.Name %>> Search(string sqlStr,List<SqlParameter> pms)
        {
            List<<%=SourceTable.Name %>> list = new List<<%=SourceTable.Name %>>();
            DataTable table = SqlHelper.ExecuteDataTable(sqlStr,pms.ToArray());
            foreach (DataRow dr in table.Rows)
            {
                <%=SourceTable.Name %> model = new <%=SourceTable.Name %>(dr);
                list.Add(model);
            }
            return list;
        }
        public static bool Insert(<%=SourceTable.Name %> model)
        {
            string sqlStr = "";
            List<string> fileds = new List<string>();
            List<string> pFileds = new List<string>();
            List<SqlParameter> pms = new List<SqlParameter>();
            #region 添加参数
            <%foreach(ColumnSchema col in SourceTable.Columns){ %>
            <%if((bool)(col.ExtendedProperties["CS_IsIdentity"].Value)==true){continue;} %>
            <%if(col.SystemType==typeof(DateTime))
            { %>
            if(model.<%=col.Name %>!=null&&model.<%=col.Name %>!=new DateTime())
            {
                fileds.Add("[<%=col.Name %>]");
                pFileds.Add("@<%=col.Name %>");
                pms.Add(new SqlParameter("<%=col.Name %>",SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>});
            }
            <% }else {%>
            <%if(!col.SystemType.IsValueType){ %>
            if(model.<%=col.Name %>!=null)
            {
                fileds.Add("[<%=col.Name %>]");
                pFileds.Add("@<%=col.Name %>");
                pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>});
            }
            <%} else{%>
            {
                fileds.Add("[<%=col.Name %>]");
                pFileds.Add("@<%=col.Name %>");
                pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>});
            }
            <%} %>
            <%} %>
            <%} %>
            #endregion
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO <%=SourceTable.Name %> (");
            sb.Append(string.Join(",", fileds));
            sb.Append(") values (");
            sb.Append(string.Join(",", pFileds));
            sb.Append(")");
            sqlStr = sb.ToString();
            int i= SqlHelper.ExecuteNonQuery(sqlStr, pms.ToArray());
            return i>0;
        }
        
        public static bool Update(<%=SourceTable.Name %> model)
        {
            string sqlStr = "";
            List<string> fileds = new List<string>();
            List<string> pFileds = new List<string>();
            List<SqlParameter> pms = new List<SqlParameter>();
            #region 添加参数
            <%foreach(ColumnSchema col in SourceTable.Columns){ %>
            <%if(col.IsPrimaryKeyMember){ %>
            pFileds.Add("[<%=col.Name %>]=@<%=col.Name %>");
            pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>});
            <%} else{%>
            <%if(col.SystemType==typeof(DateTime)){ %>
            if(model.<%=col.Name %>!=null&&model.<%=col.Name %>!=new DateTime())
            {
                fileds.Add("[<%=col.Name %>]=@<%=col.Name %>");
                pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>});
            }
            <% }else {%> 
            <%if(!col.SystemType.IsValueType){ %>
            if(model.<%=col.Name %>!=null)
            {
                fileds.Add("[<%=col.Name %>]=@<%=col.Name %>");
                pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>});
            }
            <%} else{%>
            fileds.Add("[<%=col.Name %>]=@<%=col.Name %>");
            pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>});
            <%} %>
            <%} %>
            <%} %>
            <%} %>
            #endregion
            StringBuilder sb = new StringBuilder();
            sb.Append("update <%=SourceTable.Name %> set ");
            sb.Append(string.Join(",", fileds));
            sb.Append(" where ");
            sb.Append(string.Join(" and ", pFileds));
            sqlStr = sb.ToString();
            int i= SqlHelper.ExecuteNonQuery(sqlStr, pms.ToArray());
            return i>0;
        }
    }
}
<script runat="template">
 public string Convert2Pascal(string name)
    {
        StringBuilder sb = new StringBuilder();
        string[] strs = name.Split(new char[] { '_'});
        foreach (string str in strs)
        {
            sb.Append(str.Substring(0,1).ToUpper());
            sb.Append(str.Substring(1));
        }
        return sb.ToString();
    }
public string ConvertTablename2Pascal(TableSchema table)
    {
        StringBuilder sb = new StringBuilder();
        string[] strs = table.Name.Split(new char[] { '_'});
        int index=0;
        foreach (string str in strs)
        {
//            if(index==0)
//            {
//                index++;
//                continue;
//            }
            sb.Append(str.Substring(0,1).ToUpper());
            sb.Append(str.Substring(1));
        }
        return sb.ToString();
    }
</script>
View Code

 Mapping:

<%-- 
Name:
Author: maomao
Created:<%=Datetime.Now.ToShortDateString() %>
Description: 
--%>
<%@ Template Language="C#" TargetLanguage="C#" Inherits="SqlCodeTemplate" %>
<%@ Assembly Name="Codesmith.BaseTemplates" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="CodeSmith.BaseTemplates" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Text" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="数据库" %>
<%@ Property Name="NameSpace" Type="String" Description="命名空间" %>

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

namespace <%=NameSpace %>
{
    public partial class <%=SourceTable.Name %>Map:EntityTypeConfiguration<<%=SourceTable.Name %>>
    {
        public <%=SourceTable.Name %>Map()
        {
            this.ToTable("<%=SourceTable.Name %>");
            <%if(SourceTable.HasPrimaryKey){ %>
            this.HasKey(t => new { 
            <%foreach(ColumnSchema col in SourceTable.Columns){ %>
            <%if(col.IsPrimaryKeyMember){ %>
                t.<%=col.Name %>,
            <%} %>
            <%} %>
            });
            <%} %>
        <%foreach(ColumnSchema col in SourceTable.Columns){ %>
        <%if((bool)col.ExtendedProperties["CS_isIdentity"].Value){ %>
            this.Property(t => t.<%=col.Name %>).HasColumnName("<%=col.Name %>").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        <%}else{ %>
            <%if(GetCSharpVariableType(col)=="string"&&col.Size!=-1) {%>
            this.Property(t => t.<%=col.Name %>).HasColumnName("<%=col.Name %>").HasMaxLength(<%=col.Size %>);
            <%}else{ %>
            this.Property(t => t.<%=col.Name %>).HasColumnName("<%=col.Name %>");
            <%} %>
            <%} %>
        <%} %>
        }
    }
}
<script runat="template">
 public string Convert2Pascal(ColumnSchema col)
    {
        StringBuilder sb = new StringBuilder();
        string[] strs = col.Name.Split(new char[] { '_'});
        foreach (string str in strs)
        {
            sb.Append(str.Substring(0,1).ToUpper());
            sb.Append(str.Substring(1));
        }
        return sb.ToString();
    }
 
</script>
View Code
原文地址:https://www.cnblogs.com/uptothesky/p/5488191.html