1. 程式人生 > >(17)ASP.NET Core EF基於資料模型建立資料庫

(17)ASP.NET Core EF基於資料模型建立資料庫

1.簡介

使用Entity Framework Core構建執行基本資料訪問的ASP.NET Core MVC應用程式。使用遷移(Migrations)基於資料模型建立資料庫,你可以在Windows上使用Visual Studio 2017 PowerShell或在Windows、macOS或Linux上使用.NET Core CLI來學習建立資料庫。

2.建立新專案

2.1系統必備

在建立新專案之前都要檢查是否安裝以下軟體:
●具有以下工作負載的Visual Studio 2017 15.7版或更高版本(Visual Studio必備):
  ○“ASP.NET和Web開發”(位於“Web 和雲”下)

  ○“.NET Core跨平臺開發”(位於“其他工具集”下)
●.NET Core 2.1 SDK.(Visual Studio、CLI必備)

2.2 建立專案

Core MVC專案可以通過Visual Studio手動來建立,也可以通過在CLI輸入命令列來建立,兩者區別是前者限制在Windows平臺上建立專案,後者是可以跨平臺建立專案。

2.2.1Visual Studio手動來建立專案

●開啟Visual Studio 2017
●“檔案”>“新建”>“專案”。

●從左選單中選擇“其他專案型別”>“Visual Studio 解決方案”。
●點選新建解決方案右鍵選擇“新增”>“新建專案”>“已安裝”>“Visual C#”>“.NET Core” 。
●選擇“ASP.NET Core Web 應用程式”。
●輸入“MyCoreWeb”自定義名稱,然後單擊“確定”。
●在“新建ASP.NET Core Web應用程式”對話方塊中:
  ○確保在下拉列表中選擇“.NET Core”和“ASP.NET Core 2.1”
  ○選擇“Web 應用程式(模型檢視控制器)”專案模板
  ○確保將“身份驗證”設定為“不進行身份驗證”
  ○單擊“確定”
警告:如果你使用“單獨使用者帳戶”(而不是“無”)進行身份驗證,Entity Framework Core模型會新增到Models\IdentityModel.cs中的專案。

2.2.2通過在CLI輸入命令列來建立專案

執行以下命令以建立MVC專案:

dotnet new mvc -n MyCoreWeb

更改為專案目錄,你輸入的下一個命令需要針對新專案執行:

cd MyCoreWeb

3.安裝Entity Framework Core

要安裝EF Core,請為要作為目標物件的EF Core資料庫提供程式安裝程式包。有關可用提供程式的列表,請參閱資料庫提供程式。因為我本機是用SqlServer資料庫,所以可以通過以下兩種方式安裝EF Core。

3.1在包管理器控制檯輸入命令來安裝程式包(“工具”>“NuGet包管理器”>“程式包管理器控制檯”)

install-package Microsoft.EntityFrameworkCore.SqlServer -Version 2.2.0

3.2通過在CLI輸入命令列來安裝程式包

--更改為專案所在目錄
cd /d D:\Project\MyCoreWeb
--輸入CLI命令安裝程式包
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

4.建立模型

在Models資料夾下建立BloggingContext.cs檔案,為了簡單起見,我們都將Blog、Post實體程式碼寫在BloggingContext.cs檔案中:

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options): base(options){ }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public ICollection<Post> Posts { get; set; }
}
public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

5.使用依賴注入註冊上下文

在應用程式啟動過程中,通過依賴關係注入註冊服務(如 BloggingContext),以便能夠通過建構函式的引數和屬性向使用服務的元件(如 MVC 控制器)自動提供該服務。如果想要在MVC控制器裡面呼叫BloggingContext.cs,那麼就要在Startup.cs中將其註冊為服務。

public void ConfigureServices(IServiceCollection services)
{
    var connection = @"Server=.;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
    services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
}

為簡單起見,這裡把連線字串直接在程式碼中定義。但是通常是會將連線字串放在配置檔案或環境變數中。例如:

appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "BloggingDatabase": "Server=.;Database=Blogging;Trusted_Connection=True;"
  }
} 

Startup.cs中其註冊的服務程式碼為:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}

6.遷移建立資料庫(重點)

這個章節比較重要,下面讓我們來學習下如何遷移建立資料庫。

6.1Visual Studio PowerShell手動來建立專案(“工具”>“NuGet包管理器”>“程式包管理器控制檯”)

Add-Migration InitialCreate
Update-Database

如果收到錯誤,指出The term 'add-migration' is not recognized as the name of a cmdlet,請關閉並重新開啟Visual Studio。
Add-Migration命令為遷移搭建基架,以便為模型建立一組初始表。Update-Database命令建立資料庫並向其應用程式新的遷移。
因為程式包管理器不支援PowerShell 2.0版本的遷移,需要升級到3.0版本,所以這裡就暫時演示不了,請大家自行升級3.0或以上版本測試。

6.2通過在CLI輸入命令列來遷移

--更改為專案所在目錄
cd /d D:\Project\MyCoreWeb
--遷移搭建基架
dotnet ef migrations add InitialCreate
--建立資料庫並向其應用程式新的遷移
dotnet ef database update

下面我們來看看遷移建立資料庫效果:


參考文獻:
使用新資料庫在ASP.NET Core上開始使用EF