Brad为我们提供了T4模板,因为公司一直在使用CodeSmith,故为其写了一个CodeSmith的模板,代码如下:

<%--
Name:EntityTemplates
Author:
Description:Generate a entity file in C#
--%> <%@ CodeTemplate Language="C#" TargetLanguage="Text" Src="" Inherits="" Debug="False" Description="" ResponseEncoding="UTF-8" %>
<%@ Property Name="Namespace" Type="System.String" Default="TianChenMeiKuang.Entity" Optional="False" Category="Strings" Description="实体类命名空间" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="源表" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="System.Data" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
/**********************************************************
Name:<%= GetClassName(SourceTable) %>
Author:
Date:<%=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") %>
Description:
Modify Remark:
**********************************************************/
using System;
using WebApp.Matrix.Data; namespace <%=Namespace%>
{
/// <summary>
/// This Entity is Mapping To [<%=SourceTable.Name%>] Table
/// Remark Ignore Attribute for the field when it is not need mapping
/// </summary>
[Serializable]
[TableName("[<%=SourceTable.Name%>]")]
<%
ColumnSchema primaryKeyColumn = GetPrimaryKeyColumn();
if(primaryKeyColumn != null)
{
if(Convert.ToBoolean(primaryKeyColumn.ExtendedProperties["CS_isIdentity"].Value)==true){ %>
[PrimaryKey("<%=primaryKeyColumn.Name%>", autoIncrement=true)]
<% }
else {
%>
[PrimaryKey("<%=primaryKeyColumn.Name%>", autoIncrement=false)]
<% }
}%>
public class <%= GetClassName(SourceTable) %>
{
<% for (int i = 0; i < SourceTable.Columns.Count; i++) { %>
/// <summary>
/// <%= SourceTable.Columns[i].Name %>
/// </summary>
public <%= GetCSharpVariableType(SourceTable.Columns[i]) %> <%= GetPropertyName(SourceTable.Columns[i]) %>
{
get; set;
}
<% if (i < SourceTable.Columns.Count - 1) Response.Write("\r\n"); %>
<% } %> /// <summary>
/// Equals
/// </summary>
public override bool Equals(object obj)
{
<%= GetClassName(SourceTable) %> other = obj as <%= GetClassName(SourceTable) %>;
if (<%=GetFirstKeyCondition()%>)
{
return false;
}
if (<%=GetTwoKeyCondition()%>)
{
return false;
}
return true;
}
/// <summary>
/// GetHashCode
/// </summary>
public override int GetHashCode()
{
return base.GetHashCode();
}
}
} <script runat="template">
public string GetClassName(TableSchema table)
{
string className = table.Name;
return className;
}
public string GetPropertyName(ColumnSchema column)
{
string propertyName = column.Name; return propertyName;
}
public string GetFieldName(ColumnSchema column)
{
string propertyName = column.Name;
return propertyName;
}
public ColumnSchema GetPrimaryKeyColumn()
{
for (int i = 0; i < SourceTable.Columns.Count; i++)
{
if(SourceTable.Columns[i].IsPrimaryKeyMember)
{
return SourceTable.Columns[i];
}
}
return null;
}
public string GetKey()
{
for (int i = 0; i < SourceTable.Columns.Count; i++)
{
if(SourceTable.Columns[i].IsPrimaryKeyMember)
{
return SourceTable.Columns[i].Name;
}
}
return "GetHashCode().ToString()";
}
public string GetCSharpVariableType(ColumnSchema column)
{
switch (column.DataType)
{
case DbType.AnsiString: return "string";
case DbType.AnsiStringFixedLength: return "string";
case DbType.Binary: return "Nullable<int>";
case DbType.Boolean: if(column.AllowDBNull){return "Nullable<bool>";}else{return "bool";};
case DbType.Byte: return "int";
case DbType.Currency: if(column.AllowDBNull){return "Nullable<decimal>";}else{return "decimal";};
case DbType.Date: if(column.AllowDBNull){return "Nullable<DateTime>";}else{return "DateTime";};
case DbType.DateTime: if(column.AllowDBNull){return "Nullable<DateTime>";}else{return "DateTime";};
case DbType.Decimal: if(column.AllowDBNull){return "Nullable<decimal>";}else{return "decimal";};
case DbType.Double: if(column.AllowDBNull){return "Nullable<double>";}else{return "double";};
case DbType.Guid: return "Guid";
case DbType.Int16: if(column.AllowDBNull){return "Nullable<short>";}else{return "short";};
case DbType.Int32: if(column.AllowDBNull){return "Nullable<int>";}else{return "int";};
case DbType.Int64: if(column.AllowDBNull){return "Nullable<long>";}else{return "long";};
case DbType.Object: return "object";
case DbType.SByte: if(column.AllowDBNull){return "Nullable<sbyte>";}else{return "sbyte";};
case DbType.Single: if(column.AllowDBNull){return "Nullable<float>";}else{return "float";};
case DbType.String: return "string";
case DbType.StringFixedLength: return "string";
case DbType.Time: if(column.AllowDBNull){return "Nullable<TimeSpan>";}else{return "TimeSpan";};
case DbType.UInt16: if(column.AllowDBNull){return "Nullable<ushort>";}else{return "ushort";};
case DbType.UInt32: if(column.AllowDBNull){return "Nullable<uint>";}else{return "uint";};
case DbType.UInt64: if(column.AllowDBNull){return "Nullable<ulong>";}else{return "ulong";};
case DbType.VarNumeric: if(column.AllowDBNull){return "Nullable<decimal>";}else{return "decimal";};
default:return "string";
}
}
public string GetFirstKeyCondition()
{
string condition = " other==null";
for (int i = 0; i < SourceTable.Columns.Count; i++)
{
var tempColumn = SourceTable.Columns[i];
if(tempColumn.IsPrimaryKeyMember)
{
if(((bool)tempColumn.ExtendedProperties["CS_IsIdentity"].Value))
{
condition += " || this." + SourceTable.Columns[i].Name + " == 0";
condition += " || other."+ SourceTable.Columns[i].Name + " == 0";
}
else
{
condition += " || string.IsNullOrEmpty(this." + SourceTable.Columns[i].Name + ")";
condition += " || string.IsNullOrEmpty(other."+ SourceTable.Columns[i].Name + ")";
}
}
}
return condition;
}
public string GetTwoKeyCondition()
{
string condition = " ";
for (int i = 0; i < SourceTable.Columns.Count; i++)
{
if(SourceTable.Columns[i].IsPrimaryKeyMember)
{
condition += " || this."+SourceTable.Columns[i].Name +" !=other."+SourceTable.Columns[i].Name;
}
}
return condition.Substring(4,condition.Length-4).ToString();
}
public string GetHashCodeStr()
{
string hashCode = " ";
for (int i = 0; i < SourceTable.Columns.Count; i++)
{
if(SourceTable.Columns[i].IsPrimaryKeyMember)
{
hashCode += "+\"|\" +this."+SourceTable.Columns[i].Name +".ToLower()";
}
}
return hashCode.Substring(7,hashCode.Length-7).ToString();
}
public string GetDefaultValue(ColumnSchema column)
{
string DefaultValue = "";
switch(column.DataType)
{
case DbType.Int16:
case DbType.Int32:
case DbType.Int64:
DefaultValue = "0";
break;
case DbType.Decimal:
DefaultValue = "0.000000M";
break;
case DbType.AnsiString:
case DbType.String:
case DbType.StringFixedLength:
DefaultValue = "\"\"";
break;
case DbType.Date:
case DbType.DateTime:
case DbType.DateTime2:
DefaultValue = "DateTime.Parse(\"1999-01-01 00:00:00\")";
break;
case DbType.Binary:
DefaultValue = "new byte[] { }";
break;
case DbType.Boolean:
DefaultValue = "False";
break;
case DbType.Byte:
DefaultValue = "1";
break;
default:
break;
}
return DefaultValue;
}
</script>

该模板只适用于但主键的环境,且主键必须为字符串类型,或者为自增长列。

来源:http://www.cnblogs.com/youring2

为PetaPoco添加实体模板的更多相关文章

  1. 使用T4模板为EF框架添加实体根据数据库自动生成字段注释的功能

    转自http://jeffblog.sinaapp.com/archives/501 首先我们先下载一个文件GetSummery,这里我提供了,大家可以直接下载:下载 我们在数据库建立一个表,并给表中 ...

  2. Microsoft Visual Studio 2012 添加实体数据模型

     Microsoft Visual Studio 2012 添加实体数据模型 1.创建一个web项目 2.添加ADO实体数据模型,如下图: 3.选择 从数据库生成,然后下一步 4.新建连接,如下图: ...

  3. 如何在Android Studio中添加注释模板信息?

    如何在Android Studio中添加注释模板信息? 在开发程序的时候,我们一般都会给文件自动添加上一些关于文件的注释信息,比如开发者的名字,开发的时间,开发者的联系方式等等.那么在android ...

  4. ABP框架入门踩坑-添加实体

    添加实体 ABP踩坑记录-目录 这里我以问答模块为例,记录一下我在创建实体类过程中碰到的一些坑. 审计属性 具体什么是审计属性我这里就不再介绍了,大家可以参考官方文档. 这里我是通过继承定义好的基类来 ...

  5. NetCore+Dapper WebApi架构搭建(三):添加实体和仓储

    上一节讲了类库添加一些底层的基本封装,下面来添加实体和仓储 1.Entities文件夹添加一个实体类Users,继承BaseModel,即拥有BaseModel的主键 using System; na ...

  6. OFBiz:添加实体栏位

    如何添加实体栏位?这里演示为PostalAddress添加planet栏位.打开applications/party/entitydef/entitymodel.xml,找到PostalAddress ...

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

    生成单实体模板: <%@ Template Language="C#" TargetLanguage="C#" %> <%@ Assembly ...

  8. 004-linux下配置rsyslog日志收集服务器案例 rsyslog+loganalyzer日志服务器,无法添加报表模板解决

    centos6系统 client1:192.168.1.33 centos7系统 client2:192.168.1.44 centos7系统 master:192.168.1.55 配置服务端mas ...

  9. Android Studio(六):Android Studio添加注释模板

    Android Studio相关博客: Android Studio(一):介绍.安装.配置 Android Studio(二):快捷键设置.插件安装 Android Studio(三):设置Andr ...

随机推荐

  1. docker pipework

    #!/bin/bash #auto install docker and Create VM #Define PATH Varablies IPADDR=`ifconfig |grep "B ...

  2. tomcat启动闪退

    TOMCAT启动时报错:the CATALINA_HOME environment variable is not defined correctly 运行tomcat/bin目录下的startup. ...

  3. 【iCore3 双核心板】例程三十五:HTTP_IAP_ARM实验——更新升级STM32

    实验指导书及代码包下载: http://pan.baidu.com/s/1eRgzSPW iCore3 购买链接: https://item.taobao.com/item.htm?id=524229 ...

  4. Java虚拟机内存管理机制

    自动内存管理机制 Java虚拟机(JVM)在执行Java程序过程中会把它所管理的内存划分为若干个不同的数据区域.这些区域都有各自的用途,以及创建和销毁的时间,有的区域随着虚拟机进程的启动而存在,有的区 ...

  5. soap request by afnetworking2.X/3.X

    for 2.X 参考 http://jiapumin.iteye.com/blog/2109378 AFHTTPRequestOperationManager *manager = [AFHTTPRe ...

  6. Mac OS X系统下利用VirtualBox安装和配置Windows XP虚拟机

    准备工作 下载并安装VirtualBox for Mac到https://www.virtualbox.org/wiki/Downloads下载VirtualBox <版本> for OS ...

  7. UIBezierPath用法

    前言 笔者在写本篇文章之前,也没有系统学习过贝塞尔曲线,只是曾经某一次的需求需要使用到,才临时百度看了一看而且使用最基本的功能.现在总算有时间停下来好好研究研究这个神奇而伟大的贝塞尔先生! 笔者在学习 ...

  8. Synergy 鼠标和键盘共享软件

    http://symless.com/nightly Synergy 正可以让你的多台电脑共享一套键鼠,甚至还可以共享剪贴板,如同一机多屏,并跨平台支持 .

  9. 执行带参数的sql字符串

    --要传入的参数 declare @Rv NVARCHAR(40) --要执行的带参数的sql字符串 declare  @sql nvarchar(max) set @sql='select * fr ...

  10. deleteRow

    如果是删除某一行的话,直接delete就可以,行数要在删除之前剪掉,否则会崩溃. 但是,如果section要减一的话,是不能删掉section的 Terminating app due to unca ...