Can I save an 'Object' in a SQL Server database?

C#Sql ServerSql Server-2005ado.net

C# Problem Overview


I want to save an object (of any type) into a field in a database in SQL Server 2005. Is it possible? Do I have to convert the object into something, like a byte array for example and cast it back when retrieving it?

C# Solutions


Solution 1 - C#

You can use the VARBINARY(MAX) field type in SQL Server, if you like. You can store any type of object in there, up to 2 GB in size.

To access it, you can use ADO.NET - something like this:

object yourMysteryObject = (whatever you like it to be);

MemoryStream memStream = new MemoryStream();
StreamWriter sw = new StreamWriter(memStream);

sw.Write(yourMysteryObject);

SqlCommand sqlCmd = new SqlCommand("INSERT INTO TableName(VarBinaryColumn) VALUES (@VarBinary)", sqlConnection);

sqlCmd.Parameters.Add("@VarBinary", SqlDbType.VarBinary, Int32.MaxValue);

sqlCmd.Parameters["@VarBinary"].Value = memStream.GetBuffer();

sqlCmd.ExecuteNonQuery();

Marc

Solution 2 - C#

I would use JSON to convert the object to a string, and store it in a VARCHAR or TEXT field. Not only the data is stored in a human-readable format, but it's also also readable from different languages, since pretty much every mainstream language has a JSON parser available.

The link I posted has links to several libraries in many languages (including C#), I have used this one a couple times in the past.

Solution 3 - C#

Here is an example if you are using Entity Framework (EF):

using (DbContext db = new DbContext())
{
    // The object that you want to serialize. In this case it is just an empty instance
    YourObject objectToSerialize = new YourObject();
    IFormatter formatter = new BinaryFormatter();
    using (MemoryStream stream = new MemoryStream())
    {
        formatter.Serialize(stream, objectToSerialize);
        
        // EF model. In one of its properties you store the serialized object
        YourModel modelObject = new YourModel();

        // In your model 'SerializedObject' should be of type byte[]. In the database it should be of type varbinary(MAX)
        modelObject.SerializedObject = stream.ToArray(); 
        db.YourModel.Add(modelObject);
        db.SaveChanges();
    }
}

And this is how to de-serialize the object:

// De-serialize
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream(serializedObject);
YourObject deserializedYourObject = (YourObject)formatter.Deserialize(stream);
stream.Close();

Solution 4 - C#

As others have said, serialization may be the key here (assuming you don't want to use ORM to store the properties as columns in a table, which seems much more direct).

Some caveats though; a database is:

  • long term storage
  • not related to your .NET code

As such, you do not want to use any serialization technique that is platform-specific or version-specific. You will often see people mention BinaryFormatter for persistance, but this falls into both of the above traps. You would be scuppered if you ever changed platform, or even if you just change some properties.

You need an implementation-independent approach; the simplest (which also retains the ability to be human readable) is xml or json, perhaps via XmlSerializer or Json.NET (stored in a [n]varchar(max)). If you don't care about human readable, "protocol buffers" (fast/binary) would do well (stored in a varbinary(max)), and is available for most platforms (including C#/.NET/etc).

Solution 5 - C#

To do this you need to serialize your object. You can look here at examples:

http://www.c-sharpcorner.com/UploadFile/bipinjoshi/serializingObjectsinCS11102005234746PM/serializingObjectsinCS.aspx

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAhmad FaridView Question on Stackoverflow
Solution 1 - C#marc_sView Answer on Stackoverflow
Solution 2 - C#BadaroView Answer on Stackoverflow
Solution 3 - C#Ivo StoyanovView Answer on Stackoverflow
Solution 4 - C#Marc GravellView Answer on Stackoverflow
Solution 5 - C#ThinkerView Answer on Stackoverflow