gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:15:50 25 4
gpt4 key购买 nike

<分区>

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);
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com