在ASP.NET FORUMS中一种存储和读取思路

80酷酷网    80kuku.com

  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);
总结:这种方法应该是适用于同时多个字段存入数据库,不过不是很好跟踪.

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: