Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save files in database with entity framework

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
like image 958
Freddy Avatar asked Feb 18 '10 11:02

Freddy


People also ask

How Entity Framework can save data in database in C#?

Add methods add a new entity to a context (instance of DbContext) which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students. Add(std) adds a newly created instance of the Student entity to a context with Added EntityState.

How do I upload files to Entity Framework?

Step 1: Create a MVC Application, select MVC Template and click on Ok. Step 2: Bind with Model, for that right click on project, Add, then ADO.NET Entity Data Model. Choose EF Designer from database, here we are choosing Model Contents and click on OK.


3 Answers

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

like image 63
Thomas Levesque Avatar answered Oct 22 '22 22:10

Thomas Levesque


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.

like image 42
Craig Stuntz Avatar answered Oct 22 '22 22:10

Craig Stuntz


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.

like image 5
George Stocker Avatar answered Oct 23 '22 00:10

George Stocker