简体   繁体   English

使用实体框架将文件保存在数据库中

[英]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.我有一个基于 Entity Framework 和 Microsoft SQL Server 2008 的 ASP.NET MVC 解决方案。我需要创建一个函数,让我的用户上传文件。

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数据库/表设计技巧

In your entity model, map the BLOB database column to a byte[] property.在您的实体模型中,将 BLOB 数据库列映射到byte[]属性。 Assign the content of the uploaded file to that property of the entity object, and save changes in the ObjectContext .将上传文件的内容分配给实体对象的该属性,并将更改保存在ObjectContext

To compute a hash, you can use the MD5CryptoServiceProvider class要计算哈希,您可以使用MD5CryptoServiceProvider

The "right" way to store a file in a SQL Server 2008 database is to use the FILESTREAM data type .在 SQL Server 2008 数据库中存储文件的“正确”方法是使用 FILESTREAM 数据类型 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.这样做意味着您需要通过 ASP.NET 和数据库服务器来提供可以直接从 Web 服务器提供的文件。 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.因此,当我们将文件上传到我们的 MVC/Entity Framework 时,我们只存储对数据库中文件位置的引用,并将文件本身存储在其他地方。

Obviously, which strategy is right for you depends a lot on the particulars of your application.显然,哪种策略适合您在很大程度上取决于您的应用程序的细节。

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.path存储对 Podcast 物理位置的引用。 I used a post from Scott Hanselman on File Uploads with ASP.NET MVC to deal with the file upload part.我使用了 Scott Hanselman 在File Uploads with ASP.NET MVC上的帖子来处理文件上传部分。

A working example (only for file upload because this one comes first in google) on basis of @Thomas's answer :一个基于@Thomas 的回答的工作示例(仅用于文件上传,因为这是谷歌中的第一个):

public void AddDocument(HttpPostedFileBase file)
        {
            try
            {                
                    using (TransactionScope scope = new TransactionScope())
                    {
                        try
                        {
                            using (var ctx = new Entities())
                            {

                            EntityDoc doc = new EntityDoc(); //The document table 

                            doc.DocumentFileName = file.FileName; //The file Name

                            using (var reader = new System.IO.BinaryReader(file.InputStream))
                            {
                                doc.DocumentFile = reader.ReadBytes(file.ContentLength); // the Byte [] Field
                            }
                            ctx.EntityDocs.Add(doc);


                                ctx.SaveChanges();
                                scope.Complete();
                            }
                        }
                        catch (Exception ex)
                        {                          
                            throw ex;
                        }
                    }

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM