开发者社区> 夏春涛> 正文

.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

 

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
使用WCF实现SOA面向服务编程——使用AJAX+WCF服务“.NET技术”页面开发
  在上一篇讲到,如果将BLL层的每一个类都转化为*.svc,这是一个不实在的想法。它会使服务变化复杂,难于管理。   这时候,我们第一时间想到的是23个简单开发模式中的Factory,在这里,Factory正好派上用场。
940 0
.NET数据库编程求索之路--7.使用ADO.NET实现(工厂模式-实现多数据库切换)(4)
7.使用ADO.NET实现(工厂模式-实现多数据库切换)(4) 7.7 业务逻辑层HomeShop.BLL OrderBiz.cs View Code  1 using System; 2 using System.
801 0
Asp.net MVC 使用Autofac的简单使用 IOC
Ioc(Inversion of Control)或者叫依赖注入DI(Dependency Injection) 如果一个接口有两个实现类,但是在实现过程中,用到了这两个具体的实现类。 如果采用IOC,则只能是注册一个接口类型,那么如何确保IOC在合适的时候传入不同类的实例?这是我突然间想到的一个问题,希望园友们可以帮忙解答一下!     所谓IOC(控制反转)或者说是依赖注入,就是将你设计好的类交给系统去控制,而不是在你的类内部控制,控制权发生了变化,就称为控制反转。
941 0
再不懂时序就 OUT 啦!,DBengine 排名第一时序数据库,阿里云数据库 InfluxDB 正式商业化!
阿里云数据库 InfluxDB® 版已于近日正式启动商业化 。 InfluxDB 是 DBengine 网站时序数据库类目排名第一的数据库产品,广泛应用于互联网基础资源监控,容器监控,业务运营监控分析,物联网设备远程实时监控,工业安全生产监控,生产质量评估和故障回溯。
3300 0
WPF:使用Json.NET在TreeView中树形显示JSON数据
原文  WPF:使用Json.NET在TreeView中树形显示JSON数据 据 读者可以参考这个开源的可以树形显示XML和JSON的工具: Mgen Object 603:XML/JSON树形显示小工具 或者一个更大的开源工程(构建和分析HTTP并支持XML及JSON的树形显示): Mgen Bluckbadda   效果如下: (每一个项目中的左侧黑字是数据的值,右侧灰字是数据的类型。
1900 0
.NET数据库编程求索之路--9.使用EF实现
9.使用EF实现   源码下载: /Files/SummerRain/NetDbDevRoad/9使用EF实现1自动ORM简单三层.rar /Files/SummerRain/NetDbDevRoad/9使用EF实现2自动纯POCO代理简单三层.
679 0
+关注
夏春涛
曾任教于信息工程大学16年,长期从事计算机软件与信息安全教学科研工作,目前任职于某软件公司从事技术管理工作,擅长架构设计、开发管理,对大数据、分布式颇感兴趣。
271
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
JS零基础入门教程(上册)
立即下载
性能优化方法论
立即下载
手把手学习日志服务SLS,云启实验室实战指南
立即下载