3

How can I save a file in SQL Server 2008 database with Entity Framework?

I want to use FileStream in SQL Server 2008.

2 Answers 2

6

I don't see why this wouldn't work - filestream columns are just exposed as varbinary(MAX) so you should be able to set the column using Entity Framework:

Sample from here:

Files newFile = new Files();
newFile.FileID = Guid.NewGuid();
newFile.FileContents = System.IO.File.ReadAllBytes("TextFile1.txt");
ctx.AddObject("Files", newFile);
ctx.SaveChanges();
Sign up to request clarification or add additional context in comments.

3 Comments

But this will allocate the whole file in memory, right? Is there any other reasonable way? After all, that's the whole purpose of FILESTREAM.
good point Simon - the column will be treated just like any other varbinary(MAX) column, so this approach while it works, won't be very efficient or even usable for very large files.
What I do to bypass that performance limitation is store the files in the azure blob storage then save a reference to the blob in the database.
5

Entity framework doesn't have support for SQL server specific features like filestream. You can't do it with EF you must fall back to ADO.NET.

Edit:

Undeleting my answer because I just tested how EF handles FILESTREAM columns. EF indeed works with FILESTREAM column so my answer is not fully correct and @BrokenGlass provided the solution. The problem is that EF ignores FILESTREAM keyword and doesn't really use streaming when working with FILESTREAM column. That column is handled as any other binary column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.