在ASP.NET FORUMS中一種儲存和讀取思路

來源:互聯網
上載者:User
asp.net 今天在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);
總結:這種方法應該是適用於同時多個欄位存入資料庫,不過不是很好跟蹤.



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.