2012-12-17 30 views
1

可能重複:
Save byte[] into a SQL Server database from C#如何使用C#在Sql Server 2008中存儲用戶定義的類對象?

我有一個名爲類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>(); 

現在我已序列化它並將其存儲在datababse,即,則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.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); 
} 
+0

現在我將Table更改爲LeaveDetavisable(L_ID int,leave_details varbinary(MAX))。但它顯示反序列化代碼中的錯誤爲**「Binary stream'0'不包含有效的BinaryHeader。可能的原因是序列化和反序列化之間無效的流或對象版本更改」**。變化? – akshaykumar6

回答

2

好了,你可以讀,所以它應該是相當明顯的,還是?

System.InvalidCastException:無法轉換類型 'System.String' 的目的是鍵入 'System.Byte []'。

系統化(標準的,不是XML/XAML)是二元的。因此,varchar不起作用。使用varbinary。 Varbinary返回字節數組。

+0

現在,錯誤是「Binary stream'0'不包含有效的BinaryHeader。可能的原因是序列化和反序列化之間無效的流或對象版本更改。」 – akshaykumar6

+0

如果你告訴我代碼中的問題在哪裏,那會更有幫助。謝謝!! – akshaykumar6

+0

@developer Dude,這是一個Q&A網站,而不是一個諮詢網站。你問了一個問題,得到了一個答案。想要問另一個問題,做一個代碼示例並提出一個問題。作爲一個提示 - 首先進行單元測試(總是很好),然後比較你寫入和退出的數組。 – TomTom

相關問題