Convert C# Object to and from Varbinary using Linq to SQL
-
27-05-2021 - |
Question
I want to be able to save any C# object in a single column of a SQL database table. I am not clear how to convert the object into a varbinary or get it back from a varbinary. My SystemContextObjects table has an OptionValue column that is Varbinary(max).
var dc1 = new DataContextDataContext();
var optionUpdate = dc1.SystemContextObjects.SingleOrDefault(o => o.OptionId == OptionId && o.OptionKey == OptionKey);
if (optionUpdate != null)
{
optionUpdate.OptionValue = Value; <===== NEED HELP HERE...
optionUpdate.DateCreated = DateTime.Now;
optionUpdate.PageName = PageName;
var ChangeSet = dc1.GetChangeSet();
if (ChangeSet.Updates.Count > 0)
{
dc1.SubmitChanges();
return;
}
}
Solution 2
I wound up using JSON to accomplish this. I serialize/deserialize the class to/from a string and store that. Works fine.
OTHER TIPS
You can use a binary serializer for this, e.g. using the BinaryFormatter
- but your classes must be serializable and be marked as such, here a simple example:
You have a simple Person class and mark it as serializable:
[Serializable]
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
}
You can then serialize it using a memory stream to extract a byte array representing the object:
Person p = new Person() { Name = "Fred Fish", Address = "2 Some Place" };
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, p);
ms.Position = 0;
byte[] personData = ms.ToArray(); // here's your data!
}
To re-create a Person object from a byte array you use de-serialization which works similar:
byte[] personData = ...
using (MemoryStream ms = new MemoryStream(personData))
{
BinaryFormatter formatter = new BinaryFormatter();
Person p = (Person)formatter.Deserialize(ms);
}