还是老套路,先是为一张表写模板。
<%@ Template Language="C#" TargetLanguage="C#" %> <%@ Assembly Name="SchemaExplorer"%> <%@ Import Namespace="SchemaExplorer" %> <%@ Property Name="SourceTable" Type="TableSchema"%> <%@ Property Name="ModelNameSpace" Type="System.String" Default="Model" %> <%@ Property Name="SQL_ServerDALNameSpace" Type="System.string" Default="SQL_ServerDAL" %> using System; using System.Collections.Generic; using System.Linq; using System.Text; using IDAL; using System.Data.SqlClient; using System.Data; using <%=ModelNameSpace%>; namespace <%=SQL_ServerDALNameSpace %> { public class <%=this.GetClassName()%>Service:<%=GetInterFaceName() %> { BDHelper db = new BDHelper(); //插入一条记录 void Add<%=this.GetClassName()%>(<%=this.GetClassName()%> <%=this.ToCamel(this.GetClassName())%>) { string sql = "Insert into <%=this.SourceTable.Name%> <%=GetAddSqlStatement()%>"; SqlParameter[] ps = new SqlParameter[] { <%=GetAddSQLParameters() %> }; db.ExecuteNonQury(sql,ps); } //根据主键更新 public void Update<%=this.GetClassName()%>(<%=this.GetClassName()%> <%=this.ToCamel(this.GetClassName())%>) { string sql = "Update <%=this.SourceTable.Name%> set <%=GetSetSuffix()%> where <%=GetPKSqlParameters()%>"; SqlParameter[] ps = new SqlParameter[] { <%=GetUptdateSQLParameters() %> }; db.ExecuteNonQury(sql, ps); } //根据唯一索引删除 <%foreach(IndexSchema index in this.SourceTable.Indexes){%> public void Delete<%=this.GetClassName()%>By<%=GetUniqueIndexBySuffix(index)%>(<%=GetUniqueIndexMethodParameters(index)%>) { string sql = "Delete From <%=this.SourceTable.Name%> Where <%=GetUniqueIndexSQLWhereParameters(index)%>"; SqlParameter[] ps = new SqlParameter[] { <%=GetUniqueIndexSQLParameters(index) %> }; return db.ExecuteNonQuery(sql, ps); } <%}%> //根据外键删除 <%foreach(TableKeySchema key in this.SourceTable.ForeignKeys) {%> public void Delete<%=this.GetClassName()%>By<%=GetFKBySuffix(key)%>(<%=GetFKMethodParameters(key)%>) { string sql = "Delete From <%=this.SourceTable.Name%> Where <%=GetFKSQLWhereParameters(key)%>"; SqlParameter[] ps = new SqlParameter[] { <%=GetFKSQLParameters(key) %> }; return db.ExecuteNonQuery(sql, ps); } <%}%> //根据唯一索引查询 <%foreach(IndexSchema index in this.SourceTable.Indexes){%> public <%=this.GetClassName()%> Get<%=this.GetClassName()%>By<%=GetUniqueIndexBySuffix(index)%>(<%=GetUniqueIndexMethodParameters(index)%>) { string sql = "Select * from <%=this.SourceTable.Name%> where <%=GetUniqueIndexSQLWhereParameters(index)%>"; SqlParameter[] ps = new SqlParameter[] { <%=GetUniqueIndexSQLParameters(index) %> }; DataTable dt = db.GetTable(sql,ps); if (dt.Rows.Count==0) { return null; } DataRow dr=dt.Rows[0]; <%=GetClassName() %> <%=ToCamel(GetClassName())%> = new <%=GetClassName()%>(); <%=GetUniqueIndexSelect() %> return <%=ToCamel(GetClassName())%>; } <%}%> //根据外键查询 <%foreach(TableKeySchema key in this.SourceTable.ForeignKeys) {%> public List<<%=this.GetClassName()%>> Get<%=this.GetClassName()%>By<%=GetFKBySuffix(key)%>(<%=GetFKMethodParameters(key)%>) { string sql = "Select * from <%=this.SourceTable.Name%> where <%=GetFKSQLWhereParameters(key)%>"; SqlParameter[] ps = new SqlParameter[] { <%=GetFKSQLParameters(key) %> }; DataTable dt = db.GetTable(sql,ps); DataRow dr=dt.Rows[0]; if (dt.Rows.Count==0) { return null; } <%=GetClassName() %> <%=ToCamel(GetClassName())%> = new <%=GetClassName()%>(); <%=GetUniqueIndexSelect() %> return <%=ToCamel(GetClassName())%>; } <%} %> public List<<%=this.GetClassName()%>> Get<%=this.GetClassName()%>s() { string sql = "Select * from <%=this.SourceTable.Name%>"; SqlParameter[] ps = new SqlParameter[] { }; DataTable dt = db.GetTable(sql, ps); List<<%=this.GetClassName()%>> list = new List<<%=this.GetClassName()%>>(); foreach (DataRow dr in dt.Rows) { <%=this.GetClassName()%> <%=this.ToCamel(this.GetClassName())%> = new <%=this.ToCamel(this.GetClassName())%>(); <%=GetUniqueIndexSelect() %> list.Add(<%=this.ToCamel(this.GetClassName())%>); } return list; } } } <script runat="template"> public string GetUpdateSQLStatement() { string fields=""; foreach(ColumnSchema column in this.SourceTable.Columns) { bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value; bool isPK=column.IsPrimaryKeyMember; if(!(b || isPK)) { fields+=column.Name+"=@"+column.Name+","; } } if(fields!="") { fields=fields.Substring(0,fields.Length-1); } return fields; } //更新语句的参数数组 public string GetUptdateSQLParameters() { string s=""; foreach (ColumnSchema column in this.SourceTable.Columns) { bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value; bool IsPK=column.IsPrimaryKeyMember; if (!(b && !IsPK))//参数里面:是标识列并且不是主键的列不能出现 { s+=string.Format("\t\t\t\tnew SqlParameter(\"@{0}\",{1}.{2}),\r\n",column.Name,ToCamel(this.GetClassName()),ToPascal(column.Name)); } if(s!="") { return s.Substring(0,s.Length-3).Substring(4); } } return s; } //插入语句的参数数组 public string GetAddSQLParameters() { string s=""; foreach (ColumnSchema column in this.SourceTable.Columns) { bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value; if (!b) { s+=string.Format("\t\t\t\tnew SqlParameter(\"@{0}\",{1}.{2}),\r\n",column.Name,ToCamel(this.GetClassName()),ToPascal(column.Name)); } } if (s!="") { return s.Substring(0,s.Length-3).Substring(4); } return s; } //插入语句的“()values()”部分 public string GetAddSqlStatement() { string fields=""; string values=""; //遍历所有的列名 foreach (ColumnSchema column in this.SourceTable.Columns) { //获取是否是标识列的属性 bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value; if (!b) { fields+=column.Name+","; values+="@"+column.Name+","; } } if (fields!="") { fields=fields.Substring(0,fields.Length-1); } if (values!="") { values=values.Substring(0,values.Length-1); } //利用格式化字符串的方法处理 string s=string.Format("({0})values({1})",fields,values); return s; } //根据唯一索引查询一条记录 public string GetUniqueIndexSelect() { string s=""; foreach (ColumnSchema column in this.SourceTable.Columns) { s+="\t\t\t\t"+ToCamel(GetClassName())+"."+ToPascal(column.Name) +"= ("+GetCSDataType(column)+")dr[\""+ToPascal(column.Name)+"\"];\n"; } if (s!="") { return s.Substring(0,s.Length-1).Substring(4); } return s; } //获取外键的参数列表 public string GetFKMethodParameters(TableKeySchema key) { string s=""; foreach(MemberColumnSchema column in key.ForeignKeyMemberColumns) { s+=GetCSDataType(column)+" "+ToCamel(column.Name)+","; } if(s!="") { return s.Substring(0,s.Length-1); } return s; } //得到方法名By之后的外键后缀 public string GetFKBySuffix(TableKeySchema key) { string s=""; //遍历外键成员 foreach(MemberColumnSchema column in key.ForeignKeyMemberColumns) { s+=ToPascal(column.Name)+"And"; } if(s!="") { return s.Substring(0,s.Length-3); } return s; } //获取Where之后的外键条件 public string GetFKSQLWhereParameters(TableKeySchema key) { string s=""; //遍历外键成员 foreach(MemberColumnSchema column in key.ForeignKeyMemberColumns) { s+=ToCamel(column.Name)+"=@"+ToCamel(column.Name)+" And "; } if(s!="") { return s.Substring(0,s.Length-4); } return s; } //得到根据外键查询或者删除的参数数组 public string GetFKSQLParameters(TableKeySchema key) { string s=""; foreach(MemberColumnSchema column in key.ForeignKeyMemberColumns) { s+="\t\t\t\tnew SqlParameter(\"@"+ToCamel(column.Name)+"\","+ToCamel(column.Name)+"),\r\n"; } if(s!="") { return s.Substring(0,s.Length-3).Substring(4); } return s; } //根据唯一索引查询或者删除的参数数组 public string GetUniqueIndexSQLParameters(IndexSchema index) { string s=""; //遍历所有的索引成员 foreach(MemberColumnSchema column in index.MemberColumns) { s+="\t\t\t\tnew SqlParameter(\"@"+ToCamel(column.Name)+"\","+ToCamel(column.Name)+"),\r\n"; } if(s!="") { return s.Substring(0,s.Length-3).Substring(4); } return s; } //获取根据唯一索引操作的Where条件部分 public string GetUniqueIndexSQLWhereParameters(IndexSchema index) { string s=""; //遍历所有的索引成员 foreach(MemberColumnSchema column in index.MemberColumns) { s+=ToCamel(column.Name)+"=@"+ToCamel(column.Name)+" And "; } if(s!="") { return s.Substring(0,s.Length-4); } return s; } //获取根据唯一索引操作的参数列表 public string GetUniqueIndexMethodParameters(IndexSchema index) { string s=""; //遍历所有的索引成员 foreach(MemberColumnSchema column in index.MemberColumns) { s+=GetCSDataType(column)+" "+ToCamel(column.Name)+","; } if(s!="") { return s.Substring(0,s.Length-1); } return s; } //获取根据唯一索引 public string GetUniqueIndexBySuffix(IndexSchema index) { string s=""; foreach(MemberColumnSchema column in index.MemberColumns) { s+=ToPascal(column.Name)+"And"; } if(s!="") { return s.Substring(0,s.Length-3); } return s; } //找出所有的主键(作为条件进行操作) public string GetPKSqlParameters() { string s=""; //遍历主键成员 foreach (MemberColumnSchema column in this.SourceTable.PrimaryKey.MemberColumns) { s+=ToCamel(column.Name)+"=@"+ToCamel(column.Name)+" And "; } if(s!="") { s=s.Substring(0,s.Length-4); } return s; } //得到更新语句SET后面的部分 public string GetSetSuffix() { string s=""; foreach(ColumnSchema column in this.SourceTable.Columns) { bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value; bool IsPK=column.IsPrimaryKeyMember; if (!(b||IsPK))//SET后面不能出现“是标识列或者是主键的列” { s+=ToCamel(column.Name)+"=@"+ToCamel(column.Name)+", "; } } if (s!="") { s=s.Substring(0,s.Length-2); } return s; } //得到接口的名字 public string GetInterFaceName() { string s=GetClassName(); return "I"+s+"Service"; } //Pascal命名法 public string ToPascal(string s) { return s.Substring(0,1).ToUpper()+s.Substring(1); } //Camel命名法 public string ToCamel(string s) { return s.Substring(0,1).ToLower()+s.Substring(1); } //得到实体类的类名 public string GetClassName() { string s=this.SourceTable.Name; if(s.EndsWith("s")) { return ToPascal(s.Substring(0,s.Length-1)); } return ToPascal(s); } //得到数据类型 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 string GetFileName() { return this.GetClassName()+"Service.cs"; } </script>
接下来是为整个数据库生成数据访问层:
<%@ Template Language="C#" TargetLanguage="C#" %> <%@ Assembly Name="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %> <%@ Property Name="SourceDB" Type="SchemaExplorer.DatabaseSchema" %> <%@ Register Name="ServiceTempateClass" Template="SQLServerDALService.cst" %> <% foreach (TableSchema table in this.SourceDB.Tables) { ServiceTempateClass stc=new ServiceTempateClass(); stc.SourceTable=table; stc.RenderToFile("f:\\模板类Service\\"+stc.GetFileName(),true); } %> <script runat="template"> </script>
虽然现在很辛苦,但是先苦后甜!一个功能强大模板给我们所带来的好处远远超过我们花在模板身上的时间。所以,加油!
本文出自 “Ajax的姑娘” 博客,谢绝转载!