首先创建一个sql表
create table t_rights
(
ID int not null,
Rights VarBinary(Max)
)
以下是C#代码
namespace DictionaryDemo2
{
[Serializable] //声明类可序列化
public class ModelBase
{
int _id;
string _modelName;
public int Id
{
get { return _id; }
set { _id = value; }
}
public string ModelName
{
get { return _modelName;}
set { _modelName = value; }
}
public ModelBase() { }
public ModelBase(int id, string modelName)
{
this.Id = id;
this.ModelName = modelName;
}
}
}
[Serializable] //声明类可序列化
public class Rights:ModelBase
{
string _rightsCaption;
bool _rightsState;
string _parentLevelRightsName = null;
public string RightsCaption
{
get { return _rightsCaption; }
set { _rightsCaption = value; }
}
public bool RightsState
{
get { return _rightsState; }
set { _rightsState = value; }
}
public string ParentLevelRightsName
{
get { return _parentLevelRightsName; }
set { _parentLevelRightsName = value; }
}
public Rights() { }
public Rights(int rightsId,string rightsName,string rightsCaption,bool rightsState,string parentLevelRightsName):base(rightsId,rightsName)
{
this.RightsCaption = rightsCaption;
this.RightsState =rightsState;
this.ParentLevelRightsName = parentLevelRightsName;
}
}
class Program
{
static void Main(string[] args)
{
Rights ri = new Rights();
ri.Id = 1;
ri.ModelName = "Kokeng";
ri.ParentLevelRightsName = "Administrator";
ri.RightsCaption = "fan";
ri.RightsState = false;
/* Dictionary<string, Rights> rightCollection =new Dictionary<string,Rights>();
rightCollection.Add(mb.ModelName,ri);
foreach (Rights rig in rightCollection.Values)
{
Console.WriteLine("{0},{1}",rig.ParentLevelRightsName,rig.RightsCaption);
}
Console.WriteLine("{0} \n {1}",mb.Id,mb.ModelName);*/
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms,ri);
byte[] by=new byte[(int)ms.Length];
ms.Position = 0;
ms.Read(by, 0, (int)ms.Length);
ms.Close();
string strcmd = "insert into t_Rights values(1,@byRights)";
string strConn = "Data source=.;database=Demo;UID=sa;PWD=Wi";
using (SqlConnection conn = new SqlConnection(strConn))
{
SqlCommand cmd = new SqlCommand(strcmd,conn);
SqlParameter prm1 = new SqlParameter("@byRights", SqlDbType.VarBinary, by.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, by);
cmd.Parameters.Add(prm1);
conn.Open();
if (cmd.ExecuteNonQuery() >= 1)
{
Console.WriteLine("插入数据成功");
}
else {
Console.WriteLine("插入数据失败");
}
}
Console.ReadKey();
}
}
本实例参考于CodingMouse《浅谈C# WinForm中实现基于角色的权限菜单》同时也感谢他。