如何使用C#在Sql Server 2008中存储用户定义的类对象?

时间:2012-12-17 10:49:24

标签: c# asp.net sql-server database visual-studio-2010

  

可能重复:
  Save byte[] into a SQL Server database from C#

我有一个名为 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);
}

1 个答案:

答案 0 :(得分:2)

嗯,你可以阅读,所以应该很明显,或者?

  

System.InvalidCastException:无法将类型为“System.String”的对象强制转换为类型   'System.Byte []'。

Serieaization(标准,而不是XML / XAML)是二进制的。因此,varchar不起作用。使用varbinary。 Varbinary以字节数组的形式返回。