10

学习ASP.NET Core Blazor编程系列十八——文件上传(中) - DotNet菜园

 1 year ago
source link: https://www.cnblogs.com/chillsrc/p/17018005.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

           上篇学习ASP.NET Core Blazor编程系列十七——文件上传(上)文章我们学习了如何将文件上传至服务器,但是我们并没有将文件的一些信息保存下来,无法进行查询,无法得知我们上传了一些什么文件。本篇文章演示如何将上传文件的一些基本信息保存到数据库,从而可以对上传文件进行简单管理。

三、添加FileDescribe类

            在Visual Studio 2022的解决方案资源管理器中,鼠标左键选中“Models”文件夹,右键单击,在弹出菜单中选择“添加—>类”。 将类命名为“FileDescribe”,并添加以下属性,代码如下:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Xml.Linq;
 
namespace BlazorAppDemo.Models
{
    public class FileDescribe

    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Required]

        [Key]
        public int ID { get; set; }

 

        [Display(Name = "文件名称")]

        [Required]
        [StringLength(100)] 

        public string Name { get; set; }
        [Display(Name = "上传后文件名称")]
        [StringLength(100)]
        public string NewName { get; set; }
 
 

        [Display(Name = "文件大小(bytes)")]
        [DisplayFormat(DataFormatString = "{0:N1}")]
        public long FileSize { get; set; }

 
        [Display(Name = "文件描述")]
        public string PubliceDescribe { get; set; }


        [Display(Name = "文件路径")]
        [StringLength(300)]
        public string FullName { get; set; }

        [Display(Name = "上传时间(UTC)")]
        [DisplayFormat(DataFormatString = "{0:F}")]
        [Required]
        public DateTime UploadDateTime { get; set; }


    }
}

  此类使用 Display 和 DisplayFormat 特性,有前端显示时,这些特性会生成友好的标题和格式。

四、修改BookContext

       在Visual Studio 2022的解决方案资源管理器中找到BookContext (Models/BookContext.cs) 文件,使用鼠标左键双击在文本编辑器中打开,并修改代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
 
 
namespace BlazorAppDemo.Models
{
    public class BookContext:DbContext
    {
        public BookContext(DbContextOptions<BookContext> options)
 
              : base(options)
        {
           
       }

 
        public DbSet<Book> Book { get; set; }
        public DbSet<FileDescribe> FileDescribe { get; set; }

 
    }

}

 

五、将 “FileDescribe” 类生成数据库表

   1.在Visual Studio 2022中打开程序包管理器控制台 (PMC),“菜单栏>工具> NuGet 包管理器 > 程序包管理器控制台”。

10343-20230101132840971-2026520374.png

  2.在 PMC 中分别执行以下两条命令。这两条命令将实现向数据库中添加 FileDescribe表,执行结果发下图1、与图2。

       Add-Migration AddFileDescribeTable

       Update-Database

 

10343-20230101132928202-85999542.png
10343-20230101132955076-2031210416.png

 3.在执行以上指令之后,会在数据库中添加FileDescribe表,结果如下图。

 

10343-20230101133028103-482964277.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK