我有一個新聞表和一個文件表,我想在其中保存與新聞相關的圖像或 pdf。下面是我的模型和 Create 方法,我將發布的文件保存到連接表中。但是我收到以下錯誤。這對我來說沒有意義,因為 NewsFiles 不應該是我數據庫中的對象。NewsFile 是一個表,而 NewsFiles 是虛擬集合。處理請求時數據庫操作失敗。DbUpdateException: 更新條目時出錯。有關詳細信息,請參閱內部異常。SqlException: 無效的對象名稱“NewsFiles”。ApplicationDbContext 有待處理的模型更改 在 Visual Studio 中,使用包管理器控制臺為這些更改構建新的遷移并將它們應用到數據庫:PM> Add-Migration [migration name] PM> Update-Database 或者,您可以搭建新的遷移并從項目目錄的命令提示符應用它:dotnet ef 遷移添加 [遷移名稱] dotnet ef 數據庫更新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 } } };
1 回答

holdtom
TA貢獻1805條經驗 獲得超10個贊
默認情況下:
EF Core 將為與屬性同名的上下文類中的所有 DbSet 屬性創建數據庫表
因此,您需要覆蓋默認約定。我看到你的評論builder.Entity<NewsFile>().ToTable("NewsFile")
不起作用。但我只是試了一下,它解決了這個問題。
當我評論表的顯式映射時,我得到了異常SqlException: Invalid object name 'NewsFiles'
,但它沒有說明掛起的模型更改和遷移。因此,您不知何故在模型和數據庫之間出現了不一致。正如您在評論中指出的,重建數據庫可以提供幫助
- 1 回答
- 0 關注
- 245 瀏覽
添加回答
舉報
0/150
提交
取消