c# - Asp.net Core IFormFile 类型迁移失败

标签 c# asp.net sql-server asp.net-core

我想把图片添加到Class中,但是asp.net Core迁移失败:

错误信息:
属性 Product.ImageFile 是接口(interface)类型 (IFormFile)。如果它是一个导航属性,通过将其转换为映射的实体类型来手动配置该属性的关系,否则忽略模型中的属性。

product.cs:

[Required]
[DataType(DataType.Upload)]
[FileExtensions(Extensions = "jpg,png,jpeg,bmp")]
public IFormFile ImageFile { set; get; }

图片应该怎么保存?

最佳答案

如错误所述,您不能直接使用 Entity Framework 存储接口(interface),您必须提供实际的实现类型。

如果您在 Controller 中调试并停止,您可以看到您收到的实际类型是 Microsoft.AspNetCore.Http.Internal.FormFile 因此,如果您想保存它,您应该使用此类型相反。

using Microsoft.AspNetCore.Http.Internal;
[....]
[....]
public FormFile ImageFile { set; get; }

但是无论如何,您不能将其直接保存到您的数据库中。第一个原因是因为数据可以通过这个对象的方法给出的流访问,而不是直接从属性访问。 Entity Framework 不知道如何执行该操作,它只能保存属性的值。

byte[] data;
using (var stream = file.OpenReadStream())
{
    data = new byte[stream.Length];
    stream.Read(data, 0, (int)stream.Length);
}

现在为什么要将文件直接保存在数据库中?我建议您改为将文件保存在硬盘上的某个位置,并将其路径保留在数据库中。

var filePath = myPhisicalOrRelativePath + "/" + file.FileName; //Be careful with duplicate file names
using (var fileStream = System.IO.File.Create(filePath))
{
    await file.CopyToAsync(fileStream);
}

您的产品模型将包含一个属性

public string FilePath {get; set;}

然后您必须使用 filePath 变量在 Product 对象中设置属性 FilePath

myProduct.FilePath = filePath;

如果你真的想将数据直接存储在你的数据库中而不是作为一个物理文件,我建议你可以在你的 Product 模型中添加你需要的属性而不是保存一个 FormFile 直接。

public class Product
{
    public int Id { get; set; }

    [Required]
    public byte[] FileData { get; set; }

    public string FileName { get; set; }
}

//using variables of the previous code examples
myProduct.FileData = data;
myProduct.FileName = file.FileName;

关于c# - Asp.net Core IFormFile 类型迁移失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40114277/

相关文章:

c# - 教 ANN 如何添加

c# - NuGet 版本与 SignalR 和 Owin 发生冲突

c# - "??"有什么用

c# - 更新到 ASP.NET Core 2 后无法获取配置部分

c# - Interop.Word Documents.Open 为空

mysql - 将 Distinct 子句与表达式一起使用

c# - 如何在 Guid/UNIQUEIDENTIFIER (SQL Server) 中解释 #

C# 字符串转字符串数组

c# - 如何在没有 Visual Studio 的情况下使用自定义脚本添加/更新引用?

sql - 对分层数据进行 PIVOT