2010-08-16 97 views
1

我试图做的和this question一样,但是有问题。用LINQ在SQL Server中存储二进制对象

您可以与我分享在插入和更新数据库之前您是如何准备好对象的?

我有一个List<myObject>,我想作为一个VarBinary(max)存储在SQL Server 2008中

+0

欢迎来到Stack Overflow。如果下面的答案之一帮助回答你的问题,你应该将其标记为接受的答案。 – Kelsey 2010-08-19 04:55:02

回答

2

您将需要转换您List<object>byte[]。你不需要特别的Linq,但我假设你正在使用Linq To Sql?在将对象存储在应包含二进制文件的属性中之前,需要将其转换为byte[]。这里有一些示例代码来做你需要的(Source Link):

// Convert an object to a byte array 
private byte[] ObjectToByteArray(Object obj) 
{ 
    if(obj == null) 
     return null; 
    BinaryFormatter bf = new BinaryFormatter(); 
    MemoryStream ms = new MemoryStream(); 
    bf.Serialize(ms, obj); 
    return ms.ToArray(); 
} 

// Convert a byte array to an Object 
private Object ByteArrayToObject(byte[] arrBytes) 
{ 
    MemoryStream memStream = new MemoryStream(); 
    BinaryFormatter binForm = new BinaryFormatter(); 
    memStream.Write(arrBytes, 0, arrBytes.Length); 
    memStream.Seek(0, SeekOrigin.Begin); 
    Object obj = (Object) binForm.Deserialize(memStream); 
    return obj; 
} 
+0

@ryan:这是一个很好的答案!考虑使用复选标记“接受”此答案。 – 2010-08-19 16:26:41

相关问题