亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Entity Framework Core:將上傳的文件保存到連接表

Entity Framework Core:將上傳的文件保存到連接表

C#
九州編程 2021-07-14 13:09:36
我有一個新聞表和一個文件表,我想在其中保存與新聞相關的圖像或 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',但它沒有說明掛起的模型更改和遷移。因此,您不知何故在模型和數據庫之間出現了不一致。正如您在評論中指出的,重建數據庫可以提供幫助


查看完整回答
反對 回復 2021-07-18
  • 1 回答
  • 0 關注
  • 245 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號