I faced this error while deserialization a custom object I am trying to insert a collection of custom class into sql database & retrieve it the insertion going well but retrieving the data & deserialize give me this error My code sample:
private void InsertObject()
{
ReceiptCollection items = SqlDataRepository.ReceiptProvider.GetAll();
string connectionString = "my connection";
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString);
string sql = "INSERT INTO [dbo].[LogHeader]([MasterObject]) VALUES (@MasterObject)";
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream();
binaryFormatter.Serialize(memoryStream, items);
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, connection))
{
byte[] bytes = new byte[memoryStream.Length];
memoryStream.Write(bytes, 0, bytes.Length);
connection.Open();
cmd.Parameters.AddWithValue("@MasterObject", bytes);
cmd.ExecuteNonQuery();
}
}
private void RetrieveObjects()
{
string connectionString = "my connection";
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString);
string sql = "Select MasterObject From [dbo].[LogHeader] WHERE LogHeaderID=2";
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, connection))
{
connection.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream(bytes);
memoryStream.Position = 0;
ReceiptCollection items = (ReceiptCollection)binaryFormatter.Deserialize(memoryStream); // the error happened here
}
}