3

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;
    }
}
0

2 Answers 2

8

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

I wound up using JSON to accomplish this. I serialize/deserialize the class to/from a string and store that. Works fine.

1 Comment

Can you post your solution please

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.