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

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

<分区>

Possible Duplicate:
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);
}

最佳答案

好吧,你可以阅读,所以它应该很明显,或者?

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Byte[]'.

Serieaization(标准,不是 XML/XAML)是二进制的。因此,varchar 不起作用。使用变种。 Varbinary 作为字节数组返回。

关于c# - 如何使用 C# 在 Sql Server 2008 中存储用户定义的类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13912661/

相关文章:

c# - 与 Parameters.Add 和 Parameters.AddWithValue 的区别

时间:2019-03-27 标签:c#NewtonJsonJarraychecknull/empty错误

c# - WebAPI OData 预过滤扩展查询

c# - 如何使用 IdentityUser 角色?

c# - .resx 文件或 Redis 中的语言字符串?

c# - LINQ 根据字段从一个集合中删除与另一个集合中的元素不匹配的元素

javascript - 多次提交按钮点击问题?

sql-server - 在 SQL Server 2008 中查找列中的所有特殊字符

sql-server - 选择 SQL 中的每第 n 行

python - Pandas to_sql 将列类型从 varchar 更改为 text