.NET数据库编程求索之路--4.使用ADO.NET实现(三层架构篇-使用Table传递数据)(3)

简介: 4.使用ADO.NET实现(三层架构篇-使用Table传递数据)(3)   作者:夏春涛 xchunta@163.com 转载请注明来源: http://www.cnblogs.com/SummerRain/archive/2012/07/25/2609144.

4.使用ADO.NET实现(三层架构篇-使用Table传递数据)(3)

 

作者:夏春涛 xchunta@163.com

转载请注明来源: http://www.cnblogs.com/SummerRain/archive/2012/07/25/2609144.html

4.4 数据访问层HomeShop.DAL

OrderDAO.cs

  1  using System;
  2  using System.Collections.Generic;
  3  using System.Linq;
  4  using System.Text;
  5  // 新添命名空间
  6  using System.Data;
  7  using System.Data.SqlClient;
  8  using HomeShop.DbUtility;
  9  using HomeShop.Model;
 10 
 11  namespace HomeShop.DAL
 12 {
 13      public  class OrderDAO 
 14     {
 15          protected SqlDbHelper dbHelper;
 16 
 17          public OrderDAO()
 18         {
 19              this.dbHelper =  new SqlDbHelper();
 20         }
 21 
 22          public OrderDAO( string connectionString)
 23         {
 24              this.dbHelper =  new SqlDbHelper(connectionString);
 25         }
 26 
 27          // 添加
 28           public  int Add(Order order)
 29         {
 30              int rowsCountAffected =  0;
 31             SqlTransaction trans = dbHelper.BeginTransaction();
 32              try
 33             {
 34                  // 新增订单基本信息,并使用SQL的系统函数@@IDENTITY获取新增订单的ID
 35                   string sql =  @" INSERT INTO [Order]([OrderTime],
 36                                                     [OrderStateCode],
 37                                                     [CustomerName],
 38                                                     [CustomerPhoneNo],
 39                                                     [CustomerAddress])
 40                                 VALUES(@OrderTime,
 41                                        @OrderStateCode,
 42                                        @CustomerName,
 43                                        @CustomerPhoneNo,
 44                                        @CustomerAddress)
 45                                 SET @OrderID = @@IDENTITY  ";
 46                  // @OrderID作为传出参数,用于获取新增订单的ID
 47                  SqlParameter paramOrderID =  new SqlParameter( " @OrderID ", SqlDbType.Int);
 48                 paramOrderID.Direction = ParameterDirection.Output;
 49                 SqlParameter[] parameters = {
 50                      new SqlParameter( " @OrderTime ", order.OrderTime),
 51                      new SqlParameter( " @OrderStateCode ", order.OrderStateCode),
 52                      new SqlParameter( " @CustomerName ", order.CustomerName),
 53                      new SqlParameter( " @CustomerPhoneNo ", order.CustomerPhoneNo),
 54                      new SqlParameter( " @CustomerAddress ", order.CustomerAddress),
 55                     paramOrderID};
 56                 rowsCountAffected += dbHelper.ExecuteNonQueryTrans(trans, sql, parameters);
 57                 order.OrderID = ( int)paramOrderID.Value;
 58                  // -----------------------------------------------------------
 59                   // 循环添加订购商品信息
 60                   for ( int i =  0; i < order.OrderItems.Count; i++)
 61                 {
 62                      string sqlX =  @" INSERT INTO [OrderItem]([OrderID],
 63                                                  [Product],
 64                                                  [UnitPrice],
 65                                                  [Quantity])
 66                                      VALUES( @OrderID,
 67                                              @Product,
 68                                              @UnitPrice,
 69                                              @Quantity) ";
 70                     SqlParameter[] parametersX = {
 71                          new SqlParameter( " @OrderID ", order.OrderID),
 72                          new SqlParameter( " @Product ", order.OrderItems[i].Product),
 73                          new SqlParameter( " @UnitPrice ", order.OrderItems[i].UnitPrice),
 74                          new SqlParameter( " @Quantity ", order.OrderItems[i].Quantity)};
 75                     rowsCountAffected += dbHelper.ExecuteNonQueryTrans(trans, sqlX, parametersX);
 76                 }
 77                 trans.Commit(); // 提交数据库事务
 78              }
 79              catch
 80             {
 81                 trans.Rollback(); // 回滚数据库事务
 82                   throw;
 83             }
 84             dbHelper.Close();
 85 
 86              return rowsCountAffected;
 87         }
 88 
 89          // 修改
 90           public  int Update(Order order)
 91         {
 92              int rowsCountAffected =  0;            
 93 
 94             List<SqlCmdTextAndParams> listCmdTextAndParams =  new List<SqlCmdTextAndParams>();
 95              // 修改订单基本信息
 96               string sql =  @"  UPDATE [Order]
 97                              SET [OrderTime] = @OrderTime,
 98                                  [OrderStateCode] = @OrderStateCode,
 99                                  [CustomerName] = @CustomerName,
100                                  [CustomerPhoneNo] = @CustomerPhoneNo,
101                                  [CustomerAddress] = @CustomerAddress
102                              WHERE [OrderID] = @OrderID ";
103             SqlParameter[] parameters = {
104                          new SqlParameter( " @OrderTime ", order.OrderTime),
105                          new SqlParameter( " @OrderStateCode ", order.OrderStateCode),
106                          new SqlParameter( " @CustomerName ", order.CustomerName),
107                          new SqlParameter( " @CustomerPhoneNo ", order.CustomerPhoneNo),
108                          new SqlParameter( " @CustomerAddress ", order.CustomerAddress),
109                          new SqlParameter( " @OrderID ", order.OrderID)};
110             listCmdTextAndParams.Add( new SqlCmdTextAndParams(sql, parameters));
111              // -----------------------------------------------------------
112               // 循环将订购商品信息列表同步更新到数据库中
113               // 删除
114              Order originalOrder =  this.GetSingle(order.OrderID);
115              for( int i= 0;i<originalOrder.OrderItems.Count;i++)
116             {
117                  bool exists = order.OrderItems.Exists(
118                      delegate(OrderItem item){  return (item.OrderItemID == originalOrder.OrderItems[i].OrderItemID);});
119                  if (exists)  continue;
120                 
121                  string sqlX =  @" DELETE FROM [OrderItem]
122                                  WHERE [OrderItemID] = @OrderItemID ";
123                 SqlParameter[] parametersX = {
124                                  new SqlParameter( " @OrderItemID ", originalOrder.OrderItems[i].OrderItemID)};
125                 listCmdTextAndParams.Add( new SqlCmdTextAndParams(sqlX, parametersX));                
126             }
127              // 新增/修改
128              OrderItemDAO orderItemDAO =  new OrderItemDAO();
129              for ( int i =  0; i < order.OrderItems.Count; i++)
130             {
131                  if ( 0 >= order.OrderItems[i].OrderItemID ) // 新增
132                  {
133                      string sqlX =  @" INSERT INTO [OrderItem]([OrderID],
134                                                              [Product],
135                                                              [UnitPrice],
136                                                              [Quantity])
137                                      VALUES( @OrderID,
138                                              @Product,
139                                              @UnitPrice,
140                                              @Quantity) ";
141                     SqlParameter[] parametersX = {
142                                      new SqlParameter( " @OrderID ", order.OrderID),
143                                      new SqlParameter( " @Product ", order.OrderItems[i].Product),
144                                      new SqlParameter( " @UnitPrice ", order.OrderItems[i].UnitPrice),
145                                      new SqlParameter( " @Quantity ", order.OrderItems[i].Quantity)};
146                     listCmdTextAndParams.Add( new SqlCmdTextAndParams(sqlX, parametersX));
147                 }
148                  else // 修改
149                  {
150                      string sqlX =  @" UPDATE [OrderItem]
151                                                  SET [OrderID] = @OrderID,
152                                                      [Product] = @Product,
153                                                      [UnitPrice] = @UnitPrice,
154                                                      [Quantity] = @Quantity
155                                                  WHERE [OrderItemID] = @OrderItemID ";
156                     SqlParameter[] parametersX = {
157                                      new SqlParameter( " @OrderID ", order.OrderID),
158                                      new SqlParameter( " @Product ", order.OrderItems[i].Product),
159                                      new SqlParameter( " @UnitPrice ", order.OrderItems[i].UnitPrice),
160                                      new SqlParameter( " @Quantity ", order.OrderItems[i].Quantity),
161                                      new SqlParameter( " @OrderItemID ", order.OrderItems[i].OrderItemID)};
162                     listCmdTextAndParams.Add( new SqlCmdTextAndParams(sqlX, parametersX));
163                 }
164             }
165             rowsCountAffected = dbHelper.ExecuteNonQueryTrans(listCmdTextAndParams);
166              return rowsCountAffected;
167         }
168         
169          // 删除
170           public  int Delete( int orderID)
171         {
172              string sql =  @" DELETE FROM [OrderItem]
173                             WHERE [OrderID] = @OrderID
174                             
175                             DELETE FROM [Order]
176                             WHERE [OrderID] = @OrderID  ";
177              return dbHelper.ExecuteNonQueryTrans(sql,  new SqlParameter( " @OrderID ", orderID));
178         }
179 
180          // 获取实体对象
181           public Order GetSingle( int orderID)
182         {
183              string sql =  @" SELECT * FROM [Order]
184                             WHERE [OrderID] = @OrderID ";
185             SqlParameter param =  new SqlParameter( " @OrderID ", orderID);
186             DataTable dataTable = dbHelper.ExecuteQuery(sql, param);
187 
188              return RowToModel(dataTable.Rows[ 0]);
189         }
190 
191          // 获取DataTable
192           public DataTable GetTable( string predicate,  params SqlParameter[] parameters)
193         {
194              string sql =  @" SELECT [OrderID],
195                                    [CustomerName],
196                                    [CustomerPhoneNo],
197                                    [CustomerAddress],
198                                    [OrderTime],
199                                    [OrderStateCode],
200                                    [OrderState].[Name] AS [OrderState]
201                              FROM [Order]
202                              LEFT OUTER JOIN [OrderState]
203                              ON [Order].[OrderStateCode] = [OrderState].[Code] ";
204              if ( null != predicate &&  "" != predicate.Trim())
205             {
206                 sql +=  "   WHERE   " + predicate;
207             }
208             sql +=  "  ORDER BY [OrderID] DESC  ";
209              return dbHelper.ExecuteQuery(sql, parameters);
210         }
211 
212          // 获取DataTable
213           public DataTable GetTable()
214         {
215              return GetTable( nullnull);
216         }
217 
218          // 将DataRow转换为实体对象
219           private Order RowToModel(DataRow row)
220         {
221              // ----父表
222              Order order =  new Order();
223             order.OrderID = ( int)row[ " OrderID "];
224             order.CustomerName = row[ " CustomerName "].ToString();
225             order.CustomerPhoneNo = row[ " CustomerPhoneNo "].ToString();
226             order.CustomerAddress = row[ " CustomerAddress "].ToString();
227             order.OrderTime = Convert.ToDateTime(row[ " OrderTime "]);
228             order.OrderStateCode = row[ " OrderStateCode "].ToString();
229              // ----子表----
230              OrderItemDAO orderItemDAO =  new OrderItemDAO();
231             order.OrderItems = orderItemDAO.GetList( " OrderID = @OrderID ",
232                                                      new SqlParameter( " @OrderID ", order.OrderID));
233             
234              return order;
235         }
236 
237     }
238 }

 

OrderItemDAO.cs

 1  using System;
 2  using System.Collections.Generic;
 3  using System.Linq;
 4  using System.Text;
 5  // 新添命名空间
 6  using System.Data;
 7  using System.Data.SqlClient;
 8  using HomeShop.DbUtility;
 9  using HomeShop.Model;
10 
11  namespace HomeShop.DAL
12 {
13      public  class OrderItemDAO
14     {
15          private SqlDbHelper dbHelper;
16 
17          public OrderItemDAO()
18         { 
19              this.dbHelper  =  new SqlDbHelper();
20         }
21 
22          public OrderItemDAO( string connectionString)
23         {
24              this.dbHelper =  new SqlDbHelper(connectionString);
25         }
26 
27          public  bool Exists( int orderItemID)
28         {
29             DataTable dataTable = GetTable( " OrderItemID = @OrderItemID "new SqlParameter( " @OrderItemID ", orderItemID));
30              return ( 0 != dataTable.Rows.Count);
31         }
32 
33          // 获取实体对象列表
34           public List<OrderItem> GetList( string predicate,  params SqlParameter[] parameters)
35         {
36             List<OrderItem> list =  new List<OrderItem>();
37             DataTable dataTable = GetTable(predicate, parameters);
38              for ( int i =  0; i < dataTable.Rows.Count; i++)
39             {
40                 list.Add(RowToModel(dataTable.Rows[i]));
41             }
42 
43              return list;
44         }
45 
46          // 获取DataTable
47           public DataTable GetTable( string predicate,  params SqlParameter[] parameters)
48         {
49              string sql =  @" SELECT [OrderItemID],
50                                    [OrderID],
51                                    [Product],
52                                    [UnitPrice],
53                                    [Quantity],
54                                    [UnitPrice]*[Quantity] AS SubTotal
55                             FROM [OrderItem] ";
56              if ( null != predicate &&  "" != predicate.Trim())
57             {
58                 sql +=  "   WHERE   " + predicate;
59             }
60              return dbHelper.ExecuteQuery(sql, parameters);
61         }
62 
63          // 获取DataTable
64           public DataTable GetTable()
65         {
66              return GetTable( nullnull);
67         }
68 
69          // 将DataRow转换为实体对象
70           private OrderItem RowToModel(DataRow row)
71         {
72             OrderItem orderItem =  new OrderItem();
73             orderItem.OrderID = ( int)row[ " OrderID "];
74             orderItem.OrderItemID = ( int)row[ " OrderItemID "];
75             orderItem.Product = row[ " Product "].ToString();
76             orderItem.Quantity = ( int)row[ " Quantity "];
77             orderItem.UnitPrice = ( decimal)row[ " UnitPrice "];
78 
79              return orderItem;
80         }
81     }
82 }

 

OrderStateDAO.cs

 1  using System;
 2  using System.Collections.Generic;
 3  using System.Linq;
 4  using System.Text;
 5  // 新添命名空间
 6  using System.Data;
 7  using System.Data.SqlClient;
 8  using HomeShop.DbUtility;
 9  using HomeShop.Model;
10 
11  namespace HomeShop.DAL
12 {
13      public  class OrderStateDAO
14     {
15          private SqlDbHelper dbHelper;
16 
17          public OrderStateDAO()
18         { 
19              this.dbHelper  =  new SqlDbHelper();
20         }
21 
22          public OrderStateDAO( string connectionString)
23         {
24              this.dbHelper =  new SqlDbHelper(connectionString);
25         }
26 
27          // 获取DataTable
28           public DataTable GetTable( string predicate,  params SqlParameter[] parameters)
29         {
30              string sql =  @" SELECT * FROM [OrderState] ";
31              if ( null != predicate &&  "" != predicate.Trim())
32             {
33                 sql +=  "   WHERE   " + predicate;
34             }
35             sql +=  "  ORDER BY [Code]  ";
36              return dbHelper.ExecuteQuery(sql, parameters);
37         }
38 
39          // 获取DataTable
40           public DataTable GetTable()
41         {
42              return GetTable( nullnull);
43         }
44     }
45 }

 

 

数据库文件:/Files/SummerRain/NetDbDevRoad/HomeShopDB.rar

完整源代码:/Files/SummerRain/NetDbDevRoad/4使用ADONET实现三层架构Table.rar

 

目录
相关文章
|
3月前
|
SQL 开发框架 .NET
ASP.NET连接SQL数据库:详细步骤与最佳实践指南ali01n.xinmi1009fan.com
随着Web开发技术的不断进步,ASP.NET已成为一种非常流行的Web应用程序开发框架。在ASP.NET项目中,我们经常需要与数据库进行交互,特别是SQL数据库。本文将详细介绍如何在ASP.NET项目中连接SQL数据库,并提供最佳实践指南以确保开发过程的稳定性和效率。一、准备工作在开始之前,请确保您
301 3
|
2月前
|
数据库 C# 开发者
ADO.NET连接到南大通用GBase 8s数据库
ADO.NET连接到南大通用GBase 8s数据库
|
2月前
|
存储 缓存 NoSQL
2款使用.NET开发的数据库系统
2款使用.NET开发的数据库系统
|
2月前
|
数据库连接 数据库 C#
Windows下C# 通过ADO.NET方式连接南大通用GBase 8s数据库(上)
Windows下C# 通过ADO.NET方式连接南大通用GBase 8s数据库(上)
|
2月前
|
数据库连接 数据库 C#
Windows下C# 通过ADO.NET方式连接南大通用GBase 8s数据库(下)
本文接续前文,深入讲解了在Windows环境下使用C#和ADO.NET操作南大通用GBase 8s数据库的方法。通过Visual Studio 2022创建项目,添加GBase 8s的DLL引用,并提供了详细的C#代码示例,涵盖数据库连接、表的创建与修改、数据的增删查改等操作,旨在帮助开发者提高数据库管理效率。
|
3月前
|
传感器 数据采集 物联网
探索.NET nanoFramework:为嵌入式设备编程的新途径
探索.NET nanoFramework:为嵌入式设备编程的新途
64 7
|
3月前
|
SQL XML 关系型数据库
入门指南:利用NHibernate简化.NET应用程序的数据访问
【10月更文挑战第13天】NHibernate是一个面向.NET的开源对象关系映射(ORM)工具,它提供了从数据库表到应用程序中的对象之间的映射。通过使用NHibernate,开发者可以专注于业务逻辑和领域模型的设计,而无需直接编写复杂的SQL语句来处理数据持久化问题。NHibernate支持多种数据库,并且具有高度的灵活性和可扩展性。
52 2
|
3月前
|
存储 NoSQL API
.NET NoSQL 嵌入式数据库 LiteDB 使用教程
.NET NoSQL 嵌入式数据库 LiteDB 使用教程~
|
3月前
|
SQL 开发框架 .NET
ASP.NET连接SQL数据库:实现过程与关键细节解析an3.021-6232.com
随着互联网技术的快速发展,ASP.NET作为一种广泛使用的服务器端开发技术,其与数据库的交互操作成为了应用开发中的重要环节。本文将详细介绍在ASP.NET中如何连接SQL数据库,包括连接的基本概念、实现步骤、关键代码示例以及常见问题的解决方案。由于篇幅限制,本文不能保证达到完整的2000字,但会确保
|
3月前
|
存储 分布式计算 大数据
大数据-145 Apache Kudu 架构解读 Master Table 分区 读写
大数据-145 Apache Kudu 架构解读 Master Table 分区 读写
51 0