title: Uploading Stream to Database
body: <p>I have a <code>FileForUploading</code> class which should be uploaded to a database.</p>
  
  <pre><code>public class FileForUploading
  {
      public FileForUploading(string filename, Stream stream)
      {
          this.Filename = filename;
          this.Stream = stream;
      }
  
      public string Filename { get; private set; }
  
      public Stream Stream { get; private set; }
  }
  </code></pre>
  
  <p>I am using the Entity Framework to convert it to a <code>FileForUploadingEntity</code>
  which is a very simple class  that however only contains the <code>Filename</code> property. I don't want to store the <code>Stream</code> in memory but rather upload it directly to the database.</p>
  
  <p>What would be the best way to 'stream' the <code>Stream</code> directly to the database?</p>
  
  <p>So far I have come up with this</p>
  
  <pre><code>private void UploadStream(string name, Stream stream)
      {
          var sqlQuery = @"UPDATE dbo.FilesForUpload SET Content =@content WHERE Name=@name;";
  
          var nameParameter = new SqlParameter()
          {
              ParameterName = "@name",
              Value = name
          };
  
          var contentParameter = new SqlParameter()
          {
              ParameterName = "@content",
              Value = ConvertStream(stream),
              SqlDbType = SqlDbType.Binary
          };
  
          // the database context used throughout the application.
          this.context.Database.ExecuteSqlCommand(sqlQuery, contentParameter, nameParameter);
      }
  </code></pre>
  
  <p>And here is my <code>ConvertStream</code> which converts the <code>Stream</code> to a <code>byte[]</code>. (It is stored as a <code>varbinary(MAX)</code> in the database.</p>
  
  <pre><code>private static byte[] ConvertStream(Stream stream)
      {
          using (var memoryStream = new MemoryStream())
          {
              stream.CopyTo(memoryStream);
              return memoryStream.ToArray();
          }
      }
  </code></pre>
  
  <p>Is the above solution good enough? Will it perform well if the <code>Stream</code> is large?</p>