Asp.net Core IFormFile类型迁移失败



我想将图片添加到类中,但asp.net Core迁移失败:

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

product.cs:

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

我应该如何存储图片?

正如错误所说,你不能直接在实体框架中存储接口,你必须给出一个实际的实现类型。

如果你在控制器中调试并停止,你可以看到你收到的实际类型是Microsoft.AspNetCore.Http.Internal.FormFile,所以如果你想保存它,你应该使用这个类型。

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

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

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

然后在Product对象中使用filePath变量设置属性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;

最新更新