今天在asp.net forums中發現了一種至少對于我來說特殊的存儲思路,那就是通過binaryformatter將多個字段進行圖像序列化,作為圖像存儲進數據庫,然后通過轉換成內存流再讀出來,這種做法對于需要存儲多個字段的時候,非常的方便.不用再寫一長串的變量賦值.
首先看一看,與管理設置頁面相對應的一個實例類aspnetforums.components.sitesettings()
在sitesettings()定義了
hashtable settings = new hashtable();
接下來,定義了很多的屬性,分別對應于頁面中所需要的字段,這些屬性直接對應于hashtable例如:
 public int sitesettingscachewindowinminutes {
 get {
 string key = "sitesettingscachewindowinminutes";
 if (settings[key] != null)
 return (int) settings[key];
 else
 return 15;
 }
 set {
 settings["sitesettingscachewindowinminutes"] = value;
 }
 }
也就是說他是用hashtable的方式在存儲實體字段內容,不同于我們經常使用屬性來表示.
接下來看看他是如何將這個hashtable的內容放進數據庫進去的
sqldataprovider類中有如下定義
public override void savesitesettings(sitesettings sitesettings) {
 //定義一個圖像序列化實例 
 binaryformatter binaryformatter = new binaryformatter();
 //定義一個內存流實例 
 memorystream ms = new memorystream();
 byte[] b;
 using( sqlconnection connection = getsqlconnection() ) {
 sqlcommand command = new sqlcommand(this.databaseowner + ".forums_sitesettings_save", connection);
 command.commandtype = commandtype.storedprocedure;
 //將內存流反序列,sitesettings.settings中包含有內存流中所有的標題字段
 binaryformatter.serialize(ms, sitesettings.settings);
 //重置內存流當前位置 
 ms.position = 0;
 
 b = new byte[ms.length];
 //將內存流寫入到b中
 ms.read(b, 0, b.length);
 // set the parameters
 //
 command.parameters.add("@application", sqldbtype.nvarchar, 512).value = sitesettings.sitedomain;
 command.parameters.add("@forumsdisabled", sqldbtype.smallint).value = sitesettings.forumsdisabled;
 //做為圖像存入數據庫
 command.parameters.add("@settings", sqldbtype.varbinary, 8000).value = b;
 // open the connection and exectute
 //
 connection.open();
 command.executenonquery();
 connection.close();
 }
 
 binaryformatter = null;
 ms = null;
 }
很簡單吧!不用再傳多個參數,只用先把hashtable的屬性填上,然后將其反序列化為圖像填入內存流,接著寫入byte結構,最后將這個結構實例作為二進制圖像流寫入數據庫
一句話!方便:)
從數據庫中把這些值讀出來也很容易,只需要
 binaryformatter binaryformatter = new binaryformatter();
 //上面提到的實體類
 sitesettings settings = new sitesettings();
 memorystream ms = new memorystream();
 byte[] b;
 //dr是一個datareader
 b = (byte[]) dr["settings"];
 //寫入流
 ms.write(b, 0, b.length);
 // set the memory stream position to the beginning of the stream
 //
 ms.position = 0;
 //將內存流反序列,并返回成hashtable
 settings.settings = (hashtable) binaryformatter.deserialize(ms);
總結:這種方法應該是適用于同時多個字段存入數據庫,不過不是很好跟蹤.