我有一個(gè)新聞表和一個(gè)文件表,我想在其中保存與新聞相關(guān)的圖像或 pdf。下面是我的模型和 Create 方法,我將發(fā)布的文件保存到連接表中。但是我收到以下錯(cuò)誤。這對(duì)我來說沒有意義,因?yàn)?NewsFiles 不應(yīng)該是我數(shù)據(jù)庫(kù)中的對(duì)象。NewsFile 是一個(gè)表,而 NewsFiles 是虛擬集合。處理請(qǐng)求時(shí)數(shù)據(jù)庫(kù)操作失敗。DbUpdateException: 更新條目時(shí)出錯(cuò)。有關(guān)詳細(xì)信息,請(qǐng)參閱內(nèi)部異常。SqlException: 無效的對(duì)象名稱“NewsFiles”。ApplicationDbContext 有待處理的模型更改 在 Visual Studio 中,使用包管理器控制臺(tái)為這些更改構(gòu)建新的遷移并將它們應(yīng)用到數(shù)據(jù)庫(kù):PM> Add-Migration [migration name] PM> Update-Database 或者,您可以搭建新的遷移并從項(xiàng)目目錄的命令提示符應(yīng)用它:dotnet ef 遷移添加 [遷移名稱] dotnet ef 數(shù)據(jù)庫(kù)更新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貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
默認(rèn)情況下:
EF Core 將為與屬性同名的上下文類中的所有 DbSet 屬性創(chuàng)建數(shù)據(jù)庫(kù)表
因此,您需要覆蓋默認(rèn)約定。我看到你的評(píng)論builder.Entity<NewsFile>().ToTable("NewsFile")
不起作用。但我只是試了一下,它解決了這個(gè)問題。
當(dāng)我評(píng)論表的顯式映射時(shí),我得到了異常SqlException: Invalid object name 'NewsFiles'
,但它沒有說明掛起的模型更改和遷移。因此,您不知何故在模型和數(shù)據(jù)庫(kù)之間出現(xiàn)了不一致。正如您在評(píng)論中指出的,重建數(shù)據(jù)庫(kù)可以提供幫助
- 1 回答
- 0 關(guān)注
- 243 瀏覽
添加回答
舉報(bào)
0/150
提交
取消