我有一个名为LeaveDetails.cs的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LeaveMgmt_14dec
{
[Serializable]
public class LeaveDetails
{
public string date;
public string leave_type;
}
}
然后创建了 LeaveDetails 类的对象列表。
List<LeaveDetails> Details = new List<LeaveDetails>();
现在我将它序列化并存储在数据库中,即Microsoft SQL Server 2008。
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, Details);
//Saving to db
SqlConnection con = new SqlConnection("Data Source=IND492\\SQLEXPRESS;Initial Catalog=LeaveMgmt;Integrated Security=True");
{
SqlCommand cmd = new SqlCommand("insert into LeaveDetailsTable values (@leave_details)", con);
con.Open();
byte[] bytes = new byte[ms.Length];
ms.Write(bytes, 0, bytes.Length);
cmd.Parameters.AddWithValue("@leave_details", bytes);
cmd.ExecuteNonQuery();
}
现在我怀疑在数据库中存储时应该选择哪种数据类型?实际上我使用了表 LeaveDetailsTable(L_ID int , leave_details nvarchar(50))
但是从数据库中检索时显示错误
System.InvalidCastException:无法将“System.String”类型的对象转换为“System.Byte []”类型。
从数据库中检索的代码是:
SqlConnection con = new SqlConnection("Data Source=IND492\\SQLEXPRESS;Initial Catalog=LeaveMgmt;Integrated Security=True");
{
SqlCommand cmd = new SqlCommand("select leave_details from LeaveDetailsTable where L_ID=1", con);
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
List<LeaveDetails> mc = (List<LeaveDetails>)bf.Deserialize(ms);
}