title: How to Store a User-defined Class Object in Sql Server 2008 using C#?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/4057748/save-byte-into-a-sql-server-database-from-c-sharp">Save byte[] into a SQL Server database from C#</a>  </p>
  </blockquote>
  
  
  
  <p>I have a class named <strong>LeaveDetails.cs</strong></p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>Then a created a List of Objects of LeaveDetails Class.</p>
  
  <pre><code>List&lt;LeaveDetails&gt; Details = new List&lt;LeaveDetails&gt;();
  </code></pre>
  
  <p>Now I Serialised it and stored it in the datababse, i.e. , Microsoft SQL Server 2008.</p>
  
  <pre><code>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();
              }
  </code></pre>
  
  <p>Now I have a doubt that which Datatype I should choose while Storing in database ? 
  Actually I used the table LeaveDetailsTable(L_ID int , leave_details nvarchar(50))</p>
  
  <p>But It is showing the error while retrieving from database as </p>
  
  <p><strong>System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Byte[]'.</strong></p>
  
  <p>Code for retrieving from database is :</p>
  
  <pre><code>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&lt;LeaveDetails&gt; mc = (List&lt;LeaveDetails&gt;)bf.Deserialize(ms);
  }
  </code></pre>