SqlProvider.cst 数据提供者的具体实现

本文介绍了一个使用 C# 编写的通用数据提供者模板,该模板为 .NET 应用程序提供数据库交互功能,包括创建、更新、删除和检索记录等操作。
  1None.gif<%-- 
  2None.gifName:
  3None.gifAuthor: 
  4None.gifDescription: 
  5None.gif--%>
  6None.gif<%@ CodeTemplate Language="C#" ResponseEncoding="UTF-8" TargetLanguage="Text" Src="Helper.cs" Inherits="Helper" Debug="False" Description="Template description here." %>
  7None.gif<%@ Property Name="NameSpace" Type="System.String" Default="" Optional="false" Category="1.命名空间" Description="当前生成命名空间" %>
  8None.gif<%@ Property Name="DataBase" Type="SchemaExplorer.DatabaseSchema" Category="2.数据库对象"
  9None.gif    Description="数据库对象" %>
 10None.gif<%@ Property Name="ModuleName" Type="System.String" Default="" Optional="false" Category="" Description="项目名称" %>
 11None.gif
 12None.gif<%@ Assembly Name="System.Data" %>
 13None.gif<%@ Assembly Name="SchemaExplorer" %>
 14None.gif<%@ Assembly Name="CodeSmith.BaseTemplates" %>
 15None.gif<%@ Import Namespace="System.Data" %>
 16None.gif<%@ Import Namespace="SchemaExplorer" %>
 17None.gif<%@ Import Namespace="CodeSmith.BaseTemplates" %>
 18None.gifusing System;
 19None.gifusing System.Collections.Generic;
 20None.gifusing System.Text;
 21None.gifusing System.Collections.Specialized;
 22None.gifusing System.Data;
 23None.gifusing System.Data.SqlClient;
 24None.gifusing System.Configuration.Provider;
 25None.gifusing System.Web.Configuration;
 26None.gifusing System.Diagnostics;
 27None.gifusing System.Reflection;
 28None.gif
 29None.gifnamespace <%= NameSpace%>.Providers
 30ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 31ExpandedSubBlockStart.gifContractedSubBlock.gif   /**//// <summary>
 32InBlock.gif   /// 数据提供者具体实现类
 33ExpandedSubBlockEnd.gif   /// </summary>

 34InBlock.gif   public partial class Sql<%= ModuleName%>Provider : <%= ModuleName%>Provider
 35ExpandedSubBlockStart.gifContractedSubBlock.gif   dot.gif{
 36ContractedSubBlock.gifExpandedSubBlockStart.gif      系统设置#region 系统设置
 37InBlock.gif      private string applicationName;
 38InBlock.gif      private string connectionString;
 39InBlock.gif      private string connectionStringName;
 40InBlock.gif
 41InBlock.gif
 42ExpandedSubBlockStart.gifContractedSubBlock.gif      /**//// <summary>
 43InBlock.gif      /// 设置或获取数据提供者的应用程序名称。
 44ExpandedSubBlockEnd.gif      /// </summary>

 45InBlock.gif      public override string ApplicationName
 46ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
 47ExpandedSubBlockStart.gifContractedSubBlock.gif         get dot.gifreturn applicationName; }
 48ExpandedSubBlockStart.gifContractedSubBlock.gif         set dot.gif{ applicationName = value; }
 49ExpandedSubBlockEnd.gif      }

 50InBlock.gif
 51ExpandedSubBlockStart.gifContractedSubBlock.gif      /**//// <summary>
 52InBlock.gif      /// 设置或获取数据库连接字符串名称。
 53ExpandedSubBlockEnd.gif      /// </summary>

 54InBlock.gif      public string ConnectionStringName
 55ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
 56ExpandedSubBlockStart.gifContractedSubBlock.gif         get dot.gifreturn connectionStringName; }
 57ExpandedSubBlockStart.gifContractedSubBlock.gif         set dot.gif{ connectionStringName = value; }
 58ExpandedSubBlockEnd.gif      }

 59InBlock.gif
 60ExpandedSubBlockStart.gifContractedSubBlock.gif      /**//// <summary>
 61InBlock.gif      /// 获取数据库连接字符串
 62ExpandedSubBlockEnd.gif      /// </summary>

 63InBlock.gif      public string ConnectionString
 64ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
 65InBlock.gif         //TODO测试临时改动
 66InBlock.gif         get
 67ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
 68InBlock.gif            return connectionString;
 69ExpandedSubBlockEnd.gif         }

 70ExpandedSubBlockEnd.gif      }

 71ExpandedSubBlockStart.gifContractedSubBlock.gif      /**//// <summary>
 72InBlock.gif      /// =======================
 73ExpandedSubBlockEnd.gif      /// </summary>

 74InBlock.gif      public string conn
 75ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
 76ExpandedSubBlockStart.gifContractedSubBlock.gif         set dot.gif{ connectionString = value; }
 77ExpandedSubBlockEnd.gif      }

 78InBlock.gif
 79InBlock.gif
 80InBlock.gif
 81InBlock.gif
 82ExpandedSubBlockStart.gifContractedSubBlock.gif      /**//// <summary>
 83InBlock.gif      /// 初始化数据提供者。
 84InBlock.gif      /// </summary>
 85InBlock.gif      /// <param name="name">数据提供者名称。</param>
 86ExpandedSubBlockEnd.gif      /// <param name="config">数据提供者配置信息。</param>

 87InBlock.gif      public override void Initialize(string name, NameValueCollection config)
 88ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
 89InBlock.gif         // Verify that config isn't null
 90InBlock.gif         if (config == null)
 91InBlock.gif            throw new ArgumentNullException("config");
 92InBlock.gif
 93InBlock.gif         // Assign the provider a default name if it doesn't have one
 94InBlock.gif         if (String.IsNullOrEmpty(name))
 95InBlock.gif            name = "<%= ModuleName%>Provider";
 96InBlock.gif
 97InBlock.gif         // Add a default "description" attribute to config if the
 98InBlock.gif         // attribute doesn't exist or is empty
 99InBlock.gif         if (string.IsNullOrEmpty(config["description"]))
100ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
101InBlock.gif            config.Remove("description");
102InBlock.gif            config.Add("description",
103InBlock.gif                "SQL application user provider");
104ExpandedSubBlockEnd.gif         }

105InBlock.gif
106InBlock.gif         // Call the base class's Initialize method
107InBlock.gif         base.Initialize(name, config);
108InBlock.gif
109InBlock.gif         // Initialize _applicationName
110InBlock.gif         applicationName = config["applicationName"];
111InBlock.gif
112InBlock.gif         if (string.IsNullOrEmpty(applicationName))
113InBlock.gif            applicationName = "/";
114InBlock.gif
115InBlock.gif         config.Remove("applicationName");
116InBlock.gif
117InBlock.gif         // Initialize _connectionString
118InBlock.gif         string connect = config["connectionStringName"];
119InBlock.gif
120InBlock.gif         if (String.IsNullOrEmpty(connect))
121InBlock.gif            throw new ProviderException
122InBlock.gif                ("Empty or missing connectionStringName");
123InBlock.gif
124InBlock.gif         config.Remove("connectionStringName");
125InBlock.gif
126InBlock.gif         if (WebConfigurationManager.ConnectionStrings[connect] == null)
127InBlock.gif            throw new ProviderException("Missing connection string");
128InBlock.gif
129InBlock.gif         connectionString = WebConfigurationManager.ConnectionStrings
130InBlock.gif             [connect].ConnectionString;
131InBlock.gif
132InBlock.gif         if (String.IsNullOrEmpty(connectionString))
133InBlock.gif            throw new ProviderException("Empty connection string");
134InBlock.gif
135InBlock.gif         // Throw an exception if unrecognized attributes remain
136InBlock.gif         if (config.Count > 0)
137ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
138InBlock.gif            string attr = config.GetKey(0);
139InBlock.gif            if (!String.IsNullOrEmpty(attr))
140InBlock.gif               throw new ProviderException
141InBlock.gif                   ("Unrecognized attribute: " + attr);
142ExpandedSubBlockEnd.gif         }

143ExpandedSubBlockEnd.gif      }

144ExpandedSubBlockEnd.gif      #endregion

145InBlock.gif<%
146InBlock.gif    foreach(TableSchema Table in DataBase.Tables)
147ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
148InBlock.gif%>
149InBlock.gif
150ContractedSubBlock.gifExpandedSubBlockStart.gif      %#region <%
151InBlock.gif    
152InBlock.gif    if(Table.ExtendedProperties["Rmark"!= null)
153ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
154InBlock.gif        Response.WriteLine(Table.ExtendedProperties["Rmark"].Value.ToString());
155ExpandedSubBlockEnd.gif    }

156InBlock.gif    else
157ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
158InBlock.gif        Response.WriteLine("生成时请在数据库中的扩展属性中设置key=Rmark,Value=''");
159ExpandedSubBlockEnd.gif    }
%>
160InBlock.gif
161InBlock.gif      public override <%
162InBlock.gif    if(!IsMorePrimary(Table))
163ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{%><%= GetCSharpVariableType(Table.PrimaryKey.MemberColumns[0])%> <%
164InBlock.gif        
165ExpandedSubBlockEnd.gif    }

166InBlock.gif    else
167ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{%>void <%
168ExpandedSubBlockEnd.gif    }

169InBlock.gif    %>Create<%= GetClassName(Table)%>(<%= GetClassName(Table)%> <%= GetparameteryName(Table)%>)
170ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
171InBlock.gif    <%
172InBlock.gif        if(!IsMorePrimary(Table))
173ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{%>    <%= GetCSharpVariableType(Table.PrimaryKey.MemberColumns[0])%> <%= Table.PrimaryKey.MemberColumns[0].Name%>;
174InBlock.gif    <%
175ExpandedSubBlockEnd.gif        }

176InBlock.gif    %>
177InBlock.gif         SqlConnection conn = new SqlConnection(ConnectionString);
178InBlock.gif         SqlCommand cmd = SqlHelper.PrepareCommand("<%= GetTableName(Table)%>_Create", conn, CommandType.StoredProcedure);
179InBlock.gif        <%
180InBlock.gif            if(!IsMorePrimary(Table))
181ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
182InBlock.gif        %>
183InBlock.gif         SqlHelper.MakeOutParam(cmd, "@<%= Table.PrimaryKey.MemberColumns[0].Name%>", SqlDbType.<%= GetSqlDbType(Table.PrimaryKey.MemberColumns[0])%><%= GetParamSize(Table.PrimaryKey.MemberColumns[0])%>);
184InBlock.gif        <%
185ExpandedSubBlockEnd.gif            }

186InBlock.gif            else
187ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
188InBlock.gif                foreach(ColumnSchema column in Table.PrimaryKey.MemberColumns)
189ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
190InBlock.gif        %>
191InBlock.gif         SqlHelper.MakeInParam(cmd, "@<%= column.Name%>", SqlDbType.<%=GetSqlDbType(column)%><%=GetParamSize(column)%><%= GetparameteryName(Table)%>.<%= GetPropertyName(column)%>);
192InBlock.gif        <%
193ExpandedSubBlockEnd.gif                }

194ExpandedSubBlockEnd.gif            }

195InBlock.gif            foreach(ColumnSchema column in Table.NonPrimaryKeyColumns)
196ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
197InBlock.gif                %>
198InBlock.gif         SqlHelper.MakeInParam(cmd, "@<%= column.Name%>", SqlDbType.<%=GetSqlDbType(column)%><%=GetParamSize(column)%><%= GetparameteryName(Table)%>.<%= GetPropertyName(column)%>);    
199InBlock.gif                <%
200InBlock.gif                
201ExpandedSubBlockEnd.gif            }

202InBlock.gif            
203InBlock.gif        %>
204InBlock.gif         using (conn)
205ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
206InBlock.gif            try
207ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
208InBlock.gif               conn.Open();
209InBlock.gif               cmd.ExecuteNonQuery();
210InBlock.gif            <%
211InBlock.gif            if(!IsMorePrimary(Table))
212ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
213InBlock.gif            %>
214InBlock.gif               <%= Table.PrimaryKey.MemberColumns[0].Name%> = (<%= GetCSharpVariableType(Table.PrimaryKey.MemberColumns[0])%>)cmd.Parameters["@<%= Table.PrimaryKey.MemberColumns[0].Name%>"].Value;
215InBlock.gif            <%
216ExpandedSubBlockEnd.gif            }

217InBlock.gif            %>
218ExpandedSubBlockEnd.gif            }

219InBlock.gif            catch (Exception ex)
220ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
221InBlock.gif               Debug.WriteLine(ex.Message);
222InBlock.gif               throw;
223ExpandedSubBlockEnd.gif            }

224ExpandedSubBlockEnd.gif         }

225InBlock.gif        <%
226InBlock.gif            if(!IsMorePrimary(Table))
227ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{%>return <%= Table.PrimaryKey.MemberColumns[0].Name%>;
228InBlock.gif            <%
229ExpandedSubBlockEnd.gif            }

230InBlock.gif        %>
231InBlock.gif         
232ExpandedSubBlockEnd.gif      }

233InBlock.gif      public override void Update<%= GetClassName(Table)%>(<%= GetClassName(Table)%> <%= GetparameteryName(Table)%>)
234ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
235InBlock.gif        SqlConnection conn = new SqlConnection(ConnectionString);
236InBlock.gif        SqlCommand cmd = SqlHelper.PrepareCommand("<%= GetTableName(Table)%>_Update", conn, CommandType.StoredProcedure);
237InBlock.gif<%
238InBlock.gif    foreach(ColumnSchema column in Table.Columns)
239ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
240InBlock.gif        %>
241InBlock.gif        SqlHelper.MakeInParam(cmd, "@<%= column.Name%>", SqlDbType.<%=GetSqlDbType(column)%><%=GetParamSize(column)%><%= GetparameteryName(Table)%>.<%= GetPropertyName(column)%>);
242InBlock.gif        <%
243ExpandedSubBlockEnd.gif    }

244InBlock.gif%>
245InBlock.gif         using (conn)
246ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
247InBlock.gif            try
248ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
249InBlock.gif               conn.Open();
250InBlock.gif               cmd.ExecuteNonQuery();
251ExpandedSubBlockEnd.gif            }

252InBlock.gif            catch (Exception ex)
253ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
254InBlock.gif               Debug.WriteLine(ex.Message);
255InBlock.gif               throw;
256ExpandedSubBlockEnd.gif            }

257ExpandedSubBlockEnd.gif         }

258ExpandedSubBlockEnd.gif      }

259InBlock.gif      public override void Delete<%= GetClassName(Table)%>(<% 
260InBlock.gif        foreach(ColumnSchema column in Table.PrimaryKey.MemberColumns)
261ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
262ExpandedSubBlockEnd.gif    %><%= GetCSharpVariableType(column)%> <%=GetFiledName(column)%><%= GetComma(column,Table.PrimaryKey.MemberColumns)%><%}
%>)
263ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
264InBlock.gif        SqlConnection conn = new SqlConnection(ConnectionString);
265InBlock.gif        SqlCommand cmd = SqlHelper.PrepareCommand("<%= GetTableName(Table)%>_Delete", conn, CommandType.StoredProcedure);
266InBlock.gif         <%
267InBlock.gif            foreach(ColumnSchema column in Table.PrimaryKey.MemberColumns)
268ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
269InBlock.gif        %>
270ExpandedSubBlockEnd.gif        SqlHelper.MakeInParam(cmd, "@<%= column.Name%>", SqlDbType.<%=GetSqlDbType(column)%><%=GetParamSize(column)%><%=GetFiledName(column)%>);<%}
%>
271InBlock.gif         using (conn)
272ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
273InBlock.gif            try
274ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
275InBlock.gif               conn.Open();
276InBlock.gif               cmd.ExecuteNonQuery();
277ExpandedSubBlockEnd.gif            }

278InBlock.gif            catch (Exception ex)
279ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
280InBlock.gif               Debug.WriteLine(ex.Message);
281InBlock.gif               throw;
282ExpandedSubBlockEnd.gif            }

283ExpandedSubBlockEnd.gif         }

284InBlock.gif
285ExpandedSubBlockEnd.gif      }

286InBlock.gif      public override <%= GetClassName(Table)%> Get<%= GetClassName(Table)%>(<% 
287InBlock.gif        foreach(ColumnSchema column in Table.PrimaryKey.MemberColumns)
288ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
289ExpandedSubBlockEnd.gif    %><%= GetCSharpVariableType(column)%> <%=GetFiledName(column)%><%= GetComma(column,Table.PrimaryKey.MemberColumns)%><%}
%>)
290ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
291InBlock.gif        SqlConnection conn = new SqlConnection(ConnectionString);
292InBlock.gif        SqlCommand cmd = SqlHelper.PrepareCommand("<%= GetTableName(Table)%>_Get<%= GetClassName(Table)%>", conn, CommandType.StoredProcedure);
293InBlock.gif         <%
294InBlock.gif            foreach(ColumnSchema column in Table.PrimaryKey.MemberColumns)
295ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
296InBlock.gif        %>
297ExpandedSubBlockEnd.gif        SqlHelper.MakeInParam(cmd, "@<%= column.Name%>", SqlDbType.<%=GetSqlDbType(column)%><%=GetParamSize(column)%><%=GetFiledName(column)%>);<%}
%>
298InBlock.gif        <%= GetClassName(Table)%> item = null;
299InBlock.gif
300InBlock.gif         using (conn)
301ExpandedSubBlockStart.gifContractedSubBlock.gif         dot.gif{
302InBlock.gif            try
303ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
304InBlock.gif               conn.Open();
305InBlock.gif               using (SqlDataReader reader = cmd.ExecuteReader())
306ExpandedSubBlockStart.gifContractedSubBlock.gif               dot.gif{
307InBlock.gif                  if (reader.Read())
308InBlock.gif                     item = Populate<%= GetTableName(Table)%>(reader);
309ExpandedSubBlockEnd.gif               }

310ExpandedSubBlockEnd.gif            }

311InBlock.gif            catch (Exception ex)
312ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
313InBlock.gif               Debug.WriteLine(ex.Message);
314InBlock.gif               throw;
315ExpandedSubBlockEnd.gif            }

316ExpandedSubBlockEnd.gif         }

317InBlock.gif
318InBlock.gif         return item;
319ExpandedSubBlockEnd.gif      }

320InBlock.gif      private <%= GetClassName(Table)%> Populate<%= GetTableName(Table)%>(IDataReader reader)
321ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
322InBlock.gif        <%= GetClassName(Table)%> <%= GetparameteryName(Table)%> = new <%= GetClassName(Table)%>();
323InBlock.gif        <%
324InBlock.gif        foreach(ColumnSchema column in Table.Columns)
325ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
326InBlock.gif        %>
327InBlock.gif        if (reader["<%= column.Name%>"!= DBNull.Value)
328InBlock.gif            <%= GetparameteryName(Table)%>.<%= GetPropertyName(column)%> = (<%= GetCSharpVariableType(column)%>)reader["CustomerId"];
329InBlock.gif
330ExpandedSubBlockEnd.gif         <%}
%>
331InBlock.gif         return <%= GetparameteryName(Table)%>;
332ExpandedSubBlockEnd.gif      }

333ExpandedSubBlockEnd.gif      #endregion

334InBlock.gif<%
335ExpandedSubBlockEnd.gif    }

336InBlock.gif%>
337ExpandedSubBlockEnd.gif   }

338InBlock.gif
339InBlock.gif
340InBlock.gif
341ExpandedBlockEnd.gif}

342None.gif
343None.gif<script runat="template">
344None.gifpublic string GetDBNullValue(ColumnSchema column)
345ExpandedBlockStart.gifContractedBlock.gifdot.gif{
346InBlock.gif    return "";
347ExpandedBlockEnd.gif}

348None.gif</script>

转载于:https://www.cnblogs.com/wubiyu/articles/807577.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值