Using FileStream in SQL with code first in ASP.NET Core

asp.net-core c# ef-code-first entity-framework-core

Question

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?

1
0
9/18/2019 7:46:12 PM

Popular Answer

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?

0
9/19/2019 5:14:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow