微软官方实例 RazorPagesMovie 在 asp.net core 2.1 版本下的实战
友情提示:
操作系统: MacOS 10.13.5
dotnet core: version 2.1.300
1、运行 dotnet 命令创建RazorPagesMovie项目
dotnet new webapp -o RazorPagesMovie
2、进入 RazorPagesMovie 目录,运行项目。然后,在浏览器中访问 localhost:5000 来查看项目运行情况。
cd RazorPagesMovie
dotnet run
当出现
Using launch settings from /Users/zhm/OneDrive/CodeStudy/dotnetcore/RazorPagesMovie/Properties/launchSettings.json...
: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using '/Users/zhm/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
Hosting environment: Development
Content root path: /Users/zhm/OneDrive/CodeStudy/dotnetcore/RazorPagesMovie
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
的时候,就可在浏览器里浏览项目了
3、在项目目录下新建一个Models目录,并进入目录
a、创建实体类文件Movie.cs,内容如下:
using System;
namespace RazorPagesMovie.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
}
b、创建数据上下文文件MovieContext.cs,内容如下:
using Microsoft.EntityFrameworkCore;
namespace RazorPagesMovie.Models
{
public class MovieContext : DbContext
{
public MovieContext(DbContextOptions<MovieContext> options)
: base(options)
{
}
public DbSet<Movie> Movie { get; set; }
}
}
c、打开appsetting.json文件,然后在文件中添加数据库连接字符串
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"MovieContext": "Data Source=MvcMovie.db"
}
}
4、在Startup.cs文件中,注册数据库上下文
public void ConfigureServices(IServiceCollection services)
{
// requires
// using RazorPagesMovie.Models;
// using Microsoft.EntityFrameworkCore;
services.AddDbContext<MovieContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("MovieContext")));
services.AddMvc();
}
5、安装用于进行迁移的 Entity Framework Core NuGet 包
打开 RazorPagesMovie.csproj,在里面新建一个 节点,在其中添加Microsoft.EntityFrameworkCore.Tools.DotNet工具的引用
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
</ItemGroup>
6、添加基架工具并执行初始迁移
首先,运行如下命令:
dotnet add package Microsoft.AspNetCore.Razor.Language -v 2.1.0
dotnet add package Microsoft.EntityFrameworkCore.Sqlite -v 2.1.0
dotnet add package Microsoft.EntityFrameworkCore.Tools.DotNet --version 2.1.0-preview1-final
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design -v 2.1.0
来添加package
然后,运行如下命令,来进行初始迁移:
dotnet restore
dotnet ef migrations add InitialCreate
dotnet ef database update
最终,运行
dotnet run
来运行项目,并在浏览器中使用 localhost:5000/movies 来访问。