Save files in database with entity framework
Solution 1
The "right" way to store a file in a SQL Server 2008 database is to use the FILESTREAM data type. I'm not aware that the Entity Framework supports that, but you can certainly try and see what happens.
That said, most of the time when people do this, they don't store the file in the database. Doing so means that you need to go through ASP.NET and the database server just to serve a file which you could be serving directly from the web server. It can also somewhat complicate the backup picture for your database and site. So when we upload files to our MVC/Entity Framework, we store only a reference to the file location in the database, and store the file itself elsewhere.
Obviously, which strategy is right for you depends a lot on the particulars of your application.
Solution 2
In your entity model, map the BLOB database column to a byte[]
property. Assign the content of the uploaded file to that property of the entity object, and save changes in the ObjectContext
.
To compute a hash, you can use the MD5CryptoServiceProvider
class
Solution 3
Here's how I do it for Podcasts:
ID Title Path Summary UploadDate --- ----- -------- ---------------- ----------- 1 TestPodcast /Podcasts/ep1.mp3 A test podcast 2010-02-12
The path
stores a reference to the physical location of the Podcast. I used a post from Scott Hanselman on File Uploads with ASP.NET MVC to deal with the file upload part.
Jock
Updated on July 09, 2022Comments
-
Jock almost 2 years
I have an ASP.NET MVC solution built on Entity Framework with Microsoft SQL Server 2008. I need to create a function that lets my users upload files.
What I would like is:
- A solution that uses the Entity Framework to store files in the Database
- A solution that detects and prevents from uploading the same file twice via some kind of hash/checksum
- Tips on database/table design
-
Thomas Levesque about 14 yearsWhat's wrong with that answer ? Could you at least give a reason for the downvote ? That's the one thing I really hate on SO : people who downvote without an explanation... it's so useless
-
Kevin Gauthier about 14 yearsGot no idea... but take a +1 for your trouble. :)
-
ozz almost 11 yearsThis might be ok for a small application, but assuming a complex app with backup requirements and files change over time you wouldn't be able to get back to a specific point in time
-
George Stocker almost 11 years@Ozz You're absolutely right; but this isn't meant for files that change over time. My hope is that once you release a podcast, you're not going to go back and just overwrite that podcast.
-
jocull almost 10 yearsThe bad part about this is that large files could blow up your RAM by using byte arrays instead of streams :(
-
Emaro about 5 yearsThe link is not valid anymore.