'Using FileStream in SQL with code first in ASP.NET Core
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?
Solution 1:[1]
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
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | B. Fuller |
