微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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’,但它没有说明挂起的模型更改和迁移.因此,您在某种程度上得到了模型和数据库间的不一致.正如您在评论中所述,重建数据库可以提供帮助

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐