问题
When i want to store a file in a filestream column, i always need to read the whole binary into the memory:
using (MemoryStream memoryStream = new MemoryStream())
{
sourceStream.CopyTo(memoryStream);
binaryStore.Content = memoryStream.ToArray(); //Content = filestream column
}
is there a way with the entity framework, to put the stream directly? Because, if i want to upload a large file, i get a OutOfMemoryException.
回答1:
Didn't see any update about FILESTREAM support in EF. (Mentioned before as partial support with .net 3.5 sp1 release here). I suppose entity framework is accessing FILESTREAM through TSQL and apparent that you will not be able to get the streaming performance benefits of FILESTREAM. (need to read all file content into memory)
So, the recommended approach is using with SqlFileStream
.Net API.
http://lennilobel.wordpress.com/2011/08/22/using-sqlfilestream-in-c-to-access-sql-server-filestream-data/
回答2:
EF doesn't have any support for FIlESTREAM
. It handles all interactions with FILESTREAM
as normal VARBINARY(MAX)
column so if you want to use streaming you must use ADO.NET directly.
回答3:
You can do it however it requires some manual work. Requires FILESTREAM
to be enabled.
https://docs.microsoft.com/en-us/sql/relational-databases/blob/enable-and-configure-filestream
Table, notice the unique rowguidcol not null
IdFile column that is required.
CREATE TABLE [dbo].[Files](
[id] [int] IDENTITY(1,1) NOT NULL,
[IdFile] [uniqueidentifier] unique ROWGUIDCOL NOT NULL,
[Title] [nvarchar](max) NULL,
[File] [varbinary](max) FILESTREAM NULL,
CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
[id] ASC
))
GO
ALTER TABLE [dbo].[Files] ADD CONSTRAINT [DF_Files_IdFile] DEFAULT (newid()) FOR [IdFile]
GO
EF model, IdFile column is not present, it only contains default values and is of no use for us. It is only used by SQL Server:
[Table("Files")]
public class FileModel
{
public int Id { get; set; }
public string Title { get; set; }
public byte[] File { get; set; }
}
VM:
public class FileViewModel
{
public string Title { get; set; }
public HttpPostedFileBase File { get; set; }
}
Source:
http://www.floatincode.net/post/sql-file-stream-in-asp.net-mvc-with-entity-framework
来源:https://stackoverflow.com/questions/10055280/sql-filestream-entity-framework-store-large-files