微軟官方例項 RazorPagesMovie 在 asp.net core 2.1 版本下的實戰

molisiye發表於2018-06-30

微軟官方例項 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,在裡面新建一個

  <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 來訪問。

相關文章