標籤:自己 security store gets rip www 命名 讀取 return
1.使用自動類型推斷和對象初始化器最佳化代碼
自動類型推斷和初始化器的文法知識請參考【Asp.net入門2-01】C#準系統
在實驗一中,開啟Listing.aspx.cs檔案,修改GetProducts()方法:
1 protected IEnumerable<Product> GetProducts() 2 { 3 IList<Product> products = new List<Product>(); 4 5 var sql = "select ProductID,Name,Description,Category,Price from Products"; 6 var con = new SqlConnection("Data Source=.;Initial Catalog=SportsStore;Integrated Security=True"); 7 var cmd = new SqlCommand(sql, con); 8 SqlDataReader dr; 9 10 con.Open();11 dr = cmd.ExecuteReader();12 while (dr.Read())13 {14 var prod = new Product15 {16 ProductID = dr.GetInt32(0),17 Name = dr.GetString(1),18 Description = dr.GetString(2),19 Category = dr.GetString(3),20 Price = dr.GetDecimal(4)21 };22 products.Add(prod);23 }24 return products;25 }
其中,第5、6、7行使用了自動類型推斷。第14-21使用了初始化器技術。試用了初始化器,代碼比實驗一中的代碼優雅得多。
2.添加Repository類,將資料操作從頁面分離
實驗一中,GetProducts()方法裡直接使用ADO.NET去訪問資料庫,試想一下,如果在另外一個頁面ProductManage.aspx(如產品管理頁面)中也要讀取產品列表,那麼我們不得不在ProductManage.aspx頁面中將上面的代碼重新寫一遍。同樣的代碼在程式裡多次重複地寫,很明顯這是不可取的。現在我們不該面功能,只對代碼的表現形式重新調整一下。
首先,在SportsStoreEx網站中新增加一個類:Repository。(這裡我就不再講如何給項目添加類了)。添加完之後,項目是這樣的:
第二步:編寫Repository類的代碼
開啟Repository.cs檔案,添加代碼如下:
1 using System.Collections.Generic; 2 using System.Data.SqlClient; 3 4 namespace SportStoreEx 5 { 6 public class Repository 7 { 8 public IEnumerable<Product> Products 9 {10 get11 {12 IList<Product> products = new List<Product>();13 14 var sql = "select ProductID,Name,Description,Category,Price from Products";15 var con = new SqlConnection("Data Source=.;Initial Catalog=SportsStore;Integrated Security=True");16 var cmd = new SqlCommand(sql, con);17 SqlDataReader dr;18 19 con.Open();20 dr = cmd.ExecuteReader();21 while (dr.Read())22 {23 var prod = new Product24 {25 ProductID = dr.GetInt32(0),26 Name = dr.GetString(1),27 Description = dr.GetString(2),28 Category = dr.GetString(3),29 Price = dr.GetDecimal(4)30 };31 products.Add(prod);32 }33 return products;34 }35 }36 }37 }
注意第1、2行將命名空間引用到本檔案中來,不引用的話,IEnumerable和SqlConnection等類就沒法用。
這樣,只要訪問Repository類的Products屬性,就可以得到資料庫Products表中的所有資料了。
3.修改Listing.aspx.cs檔案中GetProducts()方法
現在GetProducts()方法裡不用自己親自去資料庫讀資料了,直接向Repository類對象要Products屬性就OK啦!
protected IEnumerable<Product> GetProducts(){ Repository repository = new Repository(); return repository.Products;}
4.第一次運行最佳化後的代碼
經過前3個步驟,我們將訪問資料的代碼移植到Repository類裡面了,其它代碼均未做修改,現在運行一下,看到如下結果表示你第一次最佳化成功:
5.
實驗二:對實驗一進行最佳化代碼