使用Entity Framework Core将文件存储在数据库中 [英] Store files in database using Entity Framework Core

查看:165
本文介绍了使用Entity Framework Core将文件存储在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用ASP.NET Core应用程序中的Entity Framework Core(代码优先)将文件存储在SQL Server数据库中?

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

我尝试使用Filestream,但不幸的是我收到此错误:

I have tried using Filestream but unfortunately I get this error:

由于实体类型'UserProfile'被配置为导航属性,因此无法为其属性'Avatar'调用Property.属性只能用于配置标量属性

Cannot call Property for the property 'Avatar' on entity type 'UserProfile' because it is configured as a navigation property. Property can only be used to configure scalar properties

代码如下:

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; }
}

并映射:

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);
    }
}

我该怎么办?谢谢!

推荐答案

您可以将文件字节转换为字节数组.

You can convert the file bytes to a byte array.

public byte[] Avatar { get; set; }

以类似的方法检查EF6的可接受答案: 从以下位置保存和检索图像(二进制)使用Entity Framework 6的SQL Server

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

这篇关于使用Entity Framework Core将文件存储在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆