一、入门 使用ASP.NET Core 中的Razor Pages,以下操作通过 vs Core 完成,可以使用 visual studio 进行。
  • VS code 工具命令生产项目 Dotnet new 命令在RazorPagesMovie创建新的Razor Pages项目

    1
    Dotnet new webapp -o RazorPagesMovie
  • Code 命令在VS code的新实例打开 Razorpagesmovie 文件夹

    1
    Code -r RazorPagesMOvie
  • 运行命令新人Https开发证书 选择是

    1
    Dotne dev-certs https --trust
  • VS Code 启动Kestrel ,启动浏览器

二、生成项目文件夹的简要介绍
  • Pages 文件夹 Razor页面都是一对文件,其中包括 .cshtml 文件使用Razor语法和C#代码的Htm标记 和 .Cshtml.cs 文件,用于处理页面的C#代码。
  • Wwwroot 文件夹:包含了静态文件,如html文件、JavaScript文件和css文件和lib文件。
  • appSettings.js 包含配置数据,如链接字符串等。
  • Program.cs 包含程序的入口点
  • Startup.cs 包含配置应用行为的代码,例如,是否需要统一cookie等
  • 向Razor pages 应用添加模型

知识点:
(Entity Framework core [EF Core]) ,EF Core 是一种对象关系映射(ORM)框架,可以简化数据访问代码。模型类称为POCO类(源自“简单传统CRL对象”),因为它们和EF Core 没有任何关系。

三、模型创建、数据库上下文创建和数据库生成

  1. 添加名“Models”文件夹,将类添加到”Movie.cs” 的”Models“ 文件夹

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    using System;
    using System.ComponentModel.DataAnnotations;
    namespace RazorPagesMovie.Models {
    public class Movie {
    public int ID { get; set; }
    public string Title { get; set; }
    [DataType(DataType.Date)] //(解析 [DataType(DataType.Date)] 指定数据类型为日期)
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
    }
    }
  2. 添加数据库上下文类,将以下 RazorPagesMovieContext 类添加到“模型”Movies文件夹

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    using Microsoft.EntityFrameworkCore;
    namespace RazorPagesMovie.Models
    {
    public class RazorPagesMovieContext : DbContext
    {
    public RazorPagesMovieContext (DbContextOptions<RazorPagesMovieContext> options)
    : base(options)
    {
    }

    public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; }
    }
    }
  3. 添加数据库连接字符串,将连接字符串添加到appsetting.json 文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    {
    "Logging": {
    "LogLevel": {
    "Default": "Warning"
    }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
    "MovieContext": "Data Source=MvcMovie.db"
    }
    }
  4. 添加所需的Nuget包
    运行vs code 命令面板的Nuget命令 将SQLite和CodeGeneration.Design 添加到项目中:其中常用的添加方式有两种,方式1:选择Nuget管理工具,方式2:用命令台添加.

    1
    2
    3
    4
    //方式1
    Microsoft.EntityFrameworkCore.SQLite
    Microsoft.VisualStudio.Web.CodeGeneration.Design
    Microsoft.EntityFrameworkCore.Design

运行命令图
运行命令图
运行命令图

1
2
3
4
// 方式2 如下图可通过cmd运行
dotnet add package Microsoft.EntityFrameworkCore.SQLite
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet add package Microsoft.EntityFrameworkCore.Design

运行命令图
运行命令图

注意(无论使用Nuget还是命令行,在添加的时候注意版本统一,以免引起错误)添加成功之后可在文件 .csproj 文件查看添加的包

  1. 注册数据库上下文,将在Startup.cs 文件添加引用
    1
    2
    using RazorPagesMovie.Models;
    using Microsoft.EntityFrameworkCore;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for
// non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//begin
//使用 startp.configureServices 中的依赖关系注入容器注册数据库上下文
services.AddDbContext<RazorPagesMovieContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("MovieContext")));
//end
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
  1. 命令行执行 dotnet build 方式生成项目校验是否编译错误,如果存在错误,根据下发提示修复

  2. 搭建“电影”模型的基架

  • 7.1 在项目根目录执行命令窗口安装基架工具 代码生成器

    1
    dotnet tool install --global dotnet-aspnet-codegenerator
  • 7.2 在windows:运行命令,通过代码生成器生成代码

    1
    dotnet aspnet-codegenerator razorpage -m Movie -dc RazorPagesMovieContext -udl -outDir Pages\Movies --referenceScriptLibraries
1
2
3
4
5
6
7
8
9
10
11
12
13
//对输入的命令进行**解析**
dotnet aspnet-codegenerator razorpage
-m Movie
-dc RazorPagesMovieContext
-udl
-outDir Pages\Movies
--referenceScriptLibraries
参数 说明
-m 模型的名称。
-dc 要使用的 DbContext 类。
-udl 使用默认布局。
-outDir 用于创建视图的相对输出文件夹路径。
--referenceScriptLibraries 向“编辑”和“创建”页面添加 _ValidationScriptsPartial (添加校验脚本)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
(参考脚本库添加校验脚本)
注意可通过下面代码获取代码生成器的帮助
**cmd 输入**:
dotnet aspnet-codegenerator razorpage -h

**cmd 输出**:
Usage: aspnet-codegenerator [arguments] [options]

Arguments:
generator Name of the generator. Check available generators below.

Options:
-p|--project Path to .csproj file in the project.
-n|--nuget-package-dir
-c|--configuration Configuration for the project (Possible values: Debug/ Release)
-tfm|--target-framework Target Framework to use. (Short folder name of the tfm. eg. net46)
-b|--build-base-path
--no-build

Selected Code Generator: razorpage

Generator Arguments:
razorPageName : Name of the Razor Page
templateName : The template to use, supported view templates: 'Empty|Create|Edit|Delete|Details|List'

Generator Options:
--model|-m : Model class to use
--dataContext|-dc : DbContext class to use
--referenceScriptLibraries|-scripts : Switch to specify whether to reference script libraries in the generated views
--layout|-l : Custom Layout page to use
--useDefaultLayout|-udl : Switch to specify that default layout should be used for the views
--force|-f : Use this option to overwrite existing files
--relativeFolderPath|-outDir : Specify the relative output folder path from project where the file needs to be generated, if not specified, file will be generated in the project folder
--namespaceName|-namespace : Specify the name of the namespace to use for the generated PageModel
--partialView|-partial : Generate a partial view, other layout options (-l and -udl) are ignored if this is specified
--noPageModel|-npm : Switch to not generate a PageModel class for Empty template

用法:aspnet-codegenerator [arguments] [options]
  1. 初始迁移

    1
    2
    3
    4
    1) 运行 Dotnet core CLI 命令 
    dotnet ef migrations add InitialCreate //添加迁移
    //InitialCreate 执行一次之后再次执行会提示执行迁移记录名重复
    dotnet ef database update //更新数据模型
  2. 测试应用

  3. 注意事项
    注意调用包的版本统一性,往往不能成功是因为所调用的包高低版本冲突
    1
    2
    3
    dotnet add package Microsoft.EntityFrameworkCore.SQLite
    dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
    dotnet add package Microsoft.EntityFrameworkCore.Design

比如上面三个包调用,存在高低版本比如SQLite 2.2.0 和 SQLite 2.2.3之间差异。因此尽可能使用同一版本的包,减少不必要的麻烦。
如存在包版本异常,可使用nuget 工具 卸载之后重新选择需要的版本