3

I need to create a table and use FileStream in that table. In the SQL Server table, I need to use this column:

CREATE TABLE TestTable
(
    FileID  UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL UNIQUE DEFAULT(NEWID()),
    Pic     VARBINARY(MAX) FILESTREAM NULL
)

Now in EF Core code-first how can I create this column?

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425

2 Answers2

0

In EF core , you could not use FileStream to save file to database.

Instead, you need to convert the file to byte[](which will convert to varbinary(max) in sql server) and copy the file content over when uploading using a memory-stream for instance.

Model:

public byte[] Picture { get; set; }

Convert file to byte array:

using (var ms = new MemoryStream())
{
  file.CopyTo(ms);
  byte[] fileBytes = ms.ToArray();
  string s = Convert.ToBase64String(fileBytes);
  // act on the Base64 data
}

Refer to

Store files in database using Entity Framework Core

How to convert a file into byte array in memory?

Ryan
  • 17,241
  • 8
  • 29
  • 43
  • so from your answer it means that EF Core cannot be used to store a file as a Filestream but instead only as varbinary? – pantonis Jan 24 '20 at 14:12
0

See this solution, in which the author shows how to modify the Up() and Down() methods in an EF migration (i.e. the initial migration) to add a FILESTREAM column, and also how to perform the read/write operations.

He's using EF6, but I would think that the same could be done with EF Core.

B. Fuller
  • 157
  • 12