简体   繁体   English

使用Linq到SQL将C#Object转换为Varbinary和从Varbinary转换

[英]Convert C# Object to and from Varbinary using Linq to SQL

I want to be able to save any C# object in a single column of a SQL database table. 我希望能够将任何C#对象保存在SQL数据库表的单个列中。 I am not clear how to convert the object into a varbinary or get it back from a varbinary. 我不清楚如何将对象转换为varbinary或从varbinary中获取它。 My SystemContextObjects table has an OptionValue column that is Varbinary(max). 我的SystemContextObjects表有一个Varbinary(max)的OptionValue列。

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

You can use a binary serializer for this, eg using the BinaryFormatter - but your classes must be serializable and be marked as such, here a simple example: 你可以使用二进制序列化器,例如使用BinaryFormatter - 但是你的类必须是可序列化的并且标记为这样,这里有一个简单的例子:

You have a simple Person class and mark it as serializable: 你有一个简单的Person类,并将其标记为可序列化:

[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: 要从字节数组重新创建Person对象,请使用反序列化,其工作方式类似:

byte[] personData = ...
using (MemoryStream ms = new MemoryStream(personData))
{
    BinaryFormatter formatter = new BinaryFormatter();
    Person p = (Person)formatter.Deserialize(ms);
}

I wound up using JSON to accomplish this. 我结束了使用JSON来实现这一目标。 I serialize/deserialize the class to/from a string and store that. 我将类序列化/反序列化为字符串并将其存储起来。 Works fine. 工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM