Store files in database using Entity Framework Core

后端 未结 3 2456
-上瘾入骨i
-上瘾入骨i 2021-02-19 22:45

How to store files in a SQL Server database using Entity Framework Core (Code-First) in an ASP.NET Core app?

I have tried using Filestream but unfortunately

相关标签:
3条回答
  • 2021-02-19 23:23

    By Ef core, you can't store file in your database until now, so you can:

    1. store the result of reading files as byte[] like this :
    public byte[] Avatar { get; set; }
    
    var avatar =  File.ReadAllBytes(filePath);
    

    2.use your machine as a file server and store the path of your file in database :

    public string Avatar { get; set; }
    

    In my Opinion the second way is better and i always use this pattern but it depends on your machine's H.D.D and the amount of files you want to store.

    0 讨论(0)
  • 2021-02-19 23:25

    I am assuming that you are trying to use the windows filestream for sql server, which is not yet supported by .NET Core. You have to store the file as a byte array as already said (which will convert to varbinary(max) in sql server) and copy the file content over when uploading using a memory-stream for instance.

    0 讨论(0)
  • 2021-02-19 23:32

    You can convert the file bytes to a byte array.

    public byte[] Avatar { get; set; }
    

    Examine the accepted answer in the analogous approach for EF6: Save and retrieve image (binary) from SQL Server using Entity Framework 6

    0 讨论(0)
提交回复
热议问题