[英]Store files in database using Entity Framework Core
How to store files in a SQL Server database using Entity Framework Core (Code-First) in an ASP.NET Core app? 如何使用ASP.NET Core应用程序中的Entity Framework Core(代码优先)在SQL Server数据库中存储文件?
I have tried using Filestream
but unfortunately I get this error: 我尝试过使用
Filestream
但不幸的是我收到了这个错误:
Cannot call Property for the property 'Avatar' on entity type 'UserProfile' because it is configured as a navigation property.
无法在实体类型“UserProfile”上为属性“Avatar”调用Property,因为它已配置为导航属性。 Property can only be used to configure scalar properties
属性只能用于配置标量属性
Here's the code: 这是代码:
public class UserProfile : BaseEntity {
public FileStream Avatar { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public Sex Sex { get; set; }
public string Address { get; set; }
public string PhoneNumber { get; set; }
public virtual IEnumerable<Email> Emails { get; set; }
public virtual User User { get; set; }
public int UserID { get; set; }
}
And mapping: 并映射:
public class UserProfileMap {
public UserProfileMap(EntityTypeBuilder<UserProfile> entityBuilder) {
entityBuilder.HasKey(e => e.ID);
entityBuilder.Property(e => e.Avatar);
entityBuilder.Property(e => e.FirstName);
entityBuilder.Property(e => e.LastName);
entityBuilder.Property(e => e.DateOfBirth);
entityBuilder.Property(e => e.Sex);
entityBuilder.Property(e => e.Address);
entityBuilder.Property(e => e.PhoneNumber);
entityBuilder.HasMany(e => e.Emails).WithOne(u => u.UserProfile).HasForeignKey(x => x.UserProfileID);
}
}
What do I do? 我该怎么办? Thanks!
谢谢!
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 检查EF6的类似方法中接受的答案: 使用Entity Framework 6从SQL Server保存和检索图像(二进制)
I am assuming that you are trying to use the windows filestream for sql server, which is not yet supported by .NET Core . 我假设您正在尝试将Windows文件流用于sql server,这是.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.
您必须将文件存储为已经说过的字节数组(将在sql server中转换为varbinary(max))并在使用内存流上传时复制文件内容。
By Ef core, you can't store file in your database until now, so you can: 通过Ef核心,您现在无法将文件存储在数据库中,因此您可以:
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 : 2.将您的计算机用作文件服务器并将文件路径存储在数据库中:
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 HDD and the amount of files you want to store. 在我的意见中,第二种方式更好,我总是使用这种模式,但这取决于你的机器的硬盘和你想要存储的文件数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.