在SQL Server中存储图像的最佳方式
哪种方法可以将图像存储在SQL Server中?有没有办法用ADO.NET Entity Framework存储它们?我需要一些很好的资源,以最好和最现代的方式来做到这一点。在SQL Server中存储图像的最佳方式
如果您决定将图像存储在SQL Server中,正确的方法是使用FILESTREAM类型。
有什么方法可以用ADO.NET Entity Framework存储它们吗?
问题是,FILESTREAM是SQL Server专用列,而EF设计为数据库不可知。因此,您可以在模型上拥有byte[]
类型的属性,但EF不会利用流式传输。它会将其作为标准varbinary(max)
加载。
您也可以使用本机SqlFileStream
类直接使用ADO.NET中的FILESTREAM列类型。这是一个blog post
,它显示了一个例子。
您也可能决定将文件存储在文件系统中,并仅保存数据库中的文件路径。
您可以以varbinary格式存储图像。在sql数据库表中创建两列varbinary(MAX)
和varchar(MAX)
(您可以使用任意大小)并检查“允许空值”。
为了你的实体模型添加两个属性:
public byte[] ImageData { get; set; } //Your image stored in binary data in the database
public string ImageMimeType { get; set;) //just a string representation of Your image type,
//this property is optional)
要ImageMimeType
您可以申请HiddenInputAttribute(DisplayValue=false)
。您不需要将其应用于ImageData
,因为该框架不会为字节数组显示编辑器。
要保存图像的数据库:(正如你可以看到这里的模型对象被称为“产品”)
if (image != null) {
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
希望这有助于。
p.s.我将图像存储在文件流中,并将“文件路径”保存在数据库中。
请注意imagetype deprecation http://msdn.microsoft.com/en-us /library/ms143729.aspx – 2013-02-11 14:04:00
使用['FILESTREAM'](http://technet.microsoft.com/zh-cn/library/bb933993(v = sql.105).aspx)列类型。 – NGLN 2013-02-10 08:54:07
[要BLOB或不BLOB](http://research.microsoft.com/apps/pubs/default.aspx?id=64525) – Oded 2013-02-10 08:55:00