2013-02-10 132 views
1

哪種方法可以將圖像存儲在SQL Server中?有沒有辦法用ADO.NET Entity Framework存儲它們?我需要一些很好的資源,以最好和最現代的方式來做到這一點。在SQL Server中存儲圖像的最佳方式

+0

使用['FILESTREAM'](http://technet.microsoft.com/zh-cn/library/bb933993(v = sql.105).aspx)列類型。 – NGLN 2013-02-10 08:54:07

+4

[要BLOB或不BLOB](http://research.microsoft.com/apps/pubs/default.aspx?id=64525) – Oded 2013-02-10 08:55:00

回答

4

如果您決定將圖像存儲在SQL Server中,正確的方法是使用FILESTREAM類型。

有什麼方法可以用ADO.NET Entity Framework存儲它們嗎?

問題是,FILESTREAM是SQL Server專用列,而EF設計爲數據庫不可知。因此,您可以在模型上擁有byte[]類型的屬性,但EF不會利用流式傳輸。它會將其作爲標準varbinary(max)加載。

您也可以使用本機SqlFileStream類直接使用ADO.NET中的FILESTREAM列類型。這是一個blog post,它顯示了一個例子。

您也可能決定將文件存儲在文件系統中,並僅保存數據庫中的文件路徑。

0

您可以以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.我將圖像存儲在文件流中,並將「文件路徑」保存在數據庫中。

+0

請注意imagetype deprecation http://msdn.microsoft.com/en-us /library/ms143729.aspx – 2013-02-11 14:04:00

相關問題