我想将对象(任何类型)保存到SQL Server 2005中的数据库中的字段中。是否可能?我是否必须将对象转换为某些内容,例如字节数组,并在检索时将其转换回来?
如果您愿意,可以在SQL Server中使用VARBINARY(MAX)
字段类型。您可以在其中存储任何类型的对象,最大为2 GB。
要访问它,您可以使用ADO.NET - 如下所示:
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();
渣
正如其他人所说,序列化可能是关键(假设你不想使用ORM将属性存储为表中的列,这似乎更直接)。
但有些警告;一个数据库是:
因此,您不希望使用任何特定于平台或特定于版本的序列化技术。你会经常看到人们提到持久性的BinaryFormatter
,但这属于上述两个陷阱。如果你换过平台,或者即使你只是change some properties,你也会被打败。
您需要一种与实现无关的方法;最简单的(也保留了人类可读的能力)是xml或json,可能是通过XmlSerializer
或Json.NET(存储在[n]varchar(max)
中)。如果你不关心人类可读,“协议缓冲区”(快速/二进制)会很好(存储在varbinary(max)
中),并且是available for most platforms(包括C#/ .NET /等)。
如果您使用实体框架(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();
}
}
这是如何反序列化对象:
// De-serialize
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream(serializedObject);
YourObject deserializedYourObject = (YourObject)formatter.Deserialize(stream);
stream.Close();