c# – Entity Framework Core:将上传的文件保存到连接表中

我有一个新闻表与一个文件表连接,我想要保存与新闻相关的图像或PDF.下面是我的模型和Create方法,我将发布的文件保存到连接表中.

但是我收到以下错误.这对我没有意义,因为NewsFiles不应该是我数据库中的对象. NewsFile是一个表,NewsFiles是虚拟集合.

A database operation failed while processing the request.
DbUpdateException: An error occurred while updating the entries. See
the inner exception for details. SqlException: Invalid object name
‘NewsFiles’. There are pending model changes for ApplicationDbContext
In Visual Studio, use the Package Manager Console to scaffold a new
migration for these changes and apply them to the database:

PM> Add-Migration [migration name] PM> Update-Database Alternatively,
you can scaffold a new migration and apply it from a command prompt at
your project directory:

dotnet ef migrations add [migration name]
dotnet ef database update

public class News
{
    [Key] public int Id { get; set; }
    public string Title { get; set; }
    public virtual ICollection<NewsFile> NewsFiles { get; set; }
}

public class File
{
    [Key] public int Id { get; set; }
    public string Filename { get; set; }
    public Byte[] Content { get; set; }
    public virtual ICollection<NewsFile> NewsFiles { get; set; }
}

public class NewsFile
{
    [Key] public int Id { get; set; }
    public int NewsId { get; set; }
    public News News { get; set; }
    public int FileId { get; set; }
    public File File { get; set; }
}

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<NewsFile>().HasIndex(nf => new { nf.NewsId, nf.FileId });
    builder.Entity<NewsFile>().HasOne(nf => nf.News).WithMany(n => n.NewsFiles).HasForeignKey(nf => nf.NewsId);
    builder.Entity<NewsFile>().HasOne(nf => nf.File).WithMany(c => c.NewsFiles).HasForeignKey(pc => pc.FileId);
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(NewsViewModel model)
{
    if (ModelState.IsValid)
    {
        Byte[] file = null;
        using (var ms = new MemoryStream())
        {
            model.File.CopyTo(ms);
            file = ms.ToArray();
        }
        model.News.NewsFiles = new List<NewsFile>()
        {
            new NewsFile()
            {
                File = new Models.File() { Content = file, Filename = model.File.FileName }
            }
        };
        _dbContext.News.Add(model.News);
        await _dbContext.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(model);
}

最佳答案
By default

EF Core will create database tables for all DbSet properties in a context class with the same name as the property

因此,您需要覆盖默认约定.我看到你的评论是builder.Entity< NewsFile>().ToTable(“NewsFile”)不起作用.但我只是尝试了它,它解决了这个问题.

当我对表的显式映射进行注释时,我得到了异常SqlException:无效的对象名称’NewsFiles’,但它没有说明挂起的模型更改和迁移.因此,您在某种程度上得到了模型和数据库之间的不一致.正如您在评论中所述,重建数据库可以提供帮助

点赞