Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1082
  • Last Modified:

Serializing object into SQL database with c# csharp .net and sql server 2005

I have been able to serialize and de-serialize, using a binary formatter, an object which contains other objects successfully to file.

I want to organize all of these file in a database instead of a folder. To do this, I would like to be able to serialize directly into a database in the most efficient way possible.

I think the way I should do this is to serialize the object into a VARBINARY field (SQL Server 2005 Express).

Not sure how to code this. Below I've included some code that I currently use. Thanks for your help!
// Serialize:
BinaryFormatter bf = new BinaryFormatter();
output = File.Create(selectedFileAndPath);
bf.Serialize(output, completeTestDefinition); // Could be time consuming
 
// De-serialize:
BinaryFormatter bf = new BinaryFormatter();
input = File.OpenRead(selectedFileAndPath);
CompleteTestDefinition completeTestDefinition = (CompleteTestDefinition)bf.Deserialize(input);

Open in new window

0
yaronusa
Asked:
yaronusa
  • 4
  • 3
1 Solution
 
oobaylyCommented:
Well, you could serialise each object to a memorystream, and save the buffer to the table.
However, it'd be far more prefereable to create a db structure that duplicates your object. LINQ is probably the way to go, but to be honest I've never used it (no time like the present though)
      string connectionString = "";
      SqlCommand comm = new SqlCommand("INSERT INTO tblSerialized(fldData) VALUES(@data)",
        connectionString);
      comm.Parameters.Add("data", System.Data.SqlDbType.Binary);
 
      /* Open the command's connection & prepare the statement
       * if there are lots of items to write
       */
      comm.Connection.Open();
      comm.Prepare();
 
      List<object> objectsToSerialise = new List<object>();
      BinaryFormatter formatter = new BinaryFormatter();
      foreach (object obj in objectsToSerialise) {
        // Serialize to a memorystream
        MemoryStream ms = new MemoryStream();
        formatter.Serialize(ms, obj);
 
        // Set the binary data and execute the command
        comm.Parameters["data"].Value = ms.ToArray();
        comm.ExecuteNonQuery();
      }

Open in new window

0
 
oobaylyCommented:
Sorry, didn't initialise the command properly
0
 
oobaylyCommented:
Sorry, didn't initialise the command properly
string connectionString = "";
      SqlCommand comm = new SqlCommand("INSERT INTO tblSerialized(fldData) VALUES(@data)",
        new SqlConnection(connectionString));
      comm.Parameters.Add("data", System.Data.SqlDbType.Binary);
 
      /* Open the command's connection & prepare the statement
       * if there are lots of items to write
       */
      comm.Connection.Open();
      comm.Prepare();
 
      List<object> objectsToSerialise = new List<object>();
      BinaryFormatter formatter = new BinaryFormatter();
      foreach (object obj in objectsToSerialise) {
        // Serialize to a memorystream
        MemoryStream ms = new MemoryStream();
        formatter.Serialize(ms, obj);
 
        // Set the binary data and execute the command
        comm.Parameters["data"].Value = ms.ToArray();
        comm.ExecuteNonQuery();
      }

Open in new window

0
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 
yaronusaAuthor Commented:
OK, it seems to work as far as serializing, but I won't know until I de-serialize :)

what is the opposite of: sqlCmd.Parameters["@data"].Value = ms.ToArray();

In other words, once I have the binary data in the database, and I pull it out, how do I put it back in the object?

can you show me a couple of lines of code regarding that?

I really appreciate you helping me...
0
 
oobaylyCommented:
This should do the trick, it select all the items from the database, and deserializes each one into the generic list.
      List<object> objectsToBeDeserialized = new List<object>();
      BinaryFormatter formatter = new BinaryFormatter();
      SqlCommand comm = new SqlCommand("SELECT fldData FROM tblSerialized", new SqlConnection(connectionString));
      comm.Connection.Open();
      using (SqlDataReader reader = comm.ExecuteReader()) {
        while (reader.Read()) {
          // Deserialize from a memorystream created from the binary data
          objectsToBeDeserialized.Add(formatter.Deserialize(
            new MemoryStream((byte[])reader["fldData"])));
        }
      }
      comm.Connection.Dispose();
      comm.Dispose();

Open in new window

0
 
yaronusaAuthor Commented:
At first I couldn't get it to work because of some database issues on my end... but finally, it did work... I am amazed.

And I know that for you it probably it isn't that amazing, but on my end it is, because I wanted to make this work very badly.

Best of all, I learned a lot from your code examples.

Thank you!
0
 
yaronusaAuthor Commented:
At first I couldn't get it to work because of some database issues on my end... but finally, it did work... I am amazed.

And I know that for you it probably it isn't that amazing, but on my end it is, because I wanted to make this work very badly.

Best of all, I learned a lot from your code examples.

Thank you!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now