前提: vs的版本:Visual Studio 2017 15.3 如果不是,請運行 vs_enterprise__260723143.1491650802.exe 升級vs為最新版本。
1. 建立數據庫
在SQL 中新建查詢,輸入下面命令並執行。此命令將建立數據庫和表,並錄入三條數據。
CREATE DATABASE [Blogging];
GO
USE [Blogging];
GO
CREATE TABLE [Blog] (
[BlogId] int NOT NULL IDENTITY,
[Url] nvarchar(max) NOT NULL,
CONSTRAINT [PK_Blog] PRIMARY KEY ([BlogId])
);
GO
CREATE TABLE [Post] (
[PostId] int NOT NULL IDENTITY,
[BlogId] int NOT NULL,
[Content] nvarchar(max),
[Title] nvarchar(max),
CONSTRAINT [PK_Post] PRIMARY KEY ([PostId]),
CONSTRAINT [FK_Post_Blog_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [Blog] ([BlogId]) ON DELETE CASCADE
);
GO
INSERT INTO [Blog] (Url) VALUES
('http://blogs.msdn.com/dotnet'),
('http://blogs.msdn.com/webdev'),
('http://blogs.msdn.com/visualstudio')
GO
2. 打開vs2017,新建項目(按下面兩圖設置並確定)
Open Visual Studio 2017
- File -> New -> Project...
- From the left menu select Installed -> Templates -> Visual C# -> Web
- Select the ASP.NET Core Web Application (.NET Core) project template
- Enter EFGetStarted.AspNetCore.ExistingDb as the name and click OK
Wait for the New ASP.NET Core Web Application dialog to appear
- Under ASP.NET Core Templates 2.0 select the Web Application (Model-View-Controller)
- Ensure that Authentication is set to No Authentication
- Click OK
如此,項目模板就會自動生成,可以添加自己的代碼了。
3. 安裝項目實體模型包,以便使得項目支持從現有數據庫自動生成數據庫類。
菜單項選 工具-->NeGet包管理器-->程序包管理器控制台 單擊選定
在下面的命令窗口輸入3個命令並分別執行:
1) Install-Package Microsoft.EntityFrameworkCore.SqlServer
2)Install-Package Microsoft.EntityFrameworkCore.Tools
3)Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
繼續在命令窗口輸入下面命令,連接你的數據庫並根據你的數據庫自動生成數據庫模型類。
Scaffold-DbContext "Server=(localdb)\MSSQLLocalDB;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
解釋一下: (localdb)\MSSQLLocalDB 是數據庫服務器的名稱,Blogging是數據庫的名字。Models 是生成的數據庫類文件存放的文件夾。
如此,Models文件夾下就會自動生成數據庫模型類的文件了。
幫助信息:在Pack Manager Console中於運行如下命令:
Scaffold-DbContext "{Your DB connect string}" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
{Your DB connect string}:你的數據庫連接字符串
Microsoft.EntityFrameworkCore.SqlServer:目標數據庫為Sql Server
-OutputDir Models: 生成的文件的存放目錄,目前目錄是根目錄下的Models目錄
可以加上 -Force 命令,覆蓋已有數據庫類文件。或加上參數 -Tables Blog,Post 生成指定的表的類。
語法:
Scaffold-DbContext [-Connection] <String> [-Provider] <String> [-OutputDir <String>] [-Context <String>] [-Schemas <String[]>] [-Tables <String[]>] [-DataAnnotations] [
-Force] [-Project <String>] [-StartupProject <String>] [<CommonParameters>]
可輸入 Scaffold-DbContext -? 選N查看幫助
Install Entity Framework
To use EF Core, install the package for the database provider(s) you want to target. This walkthrough uses SQL Server. For a list of available providers see Database Providers.
-
Tools > NuGet Package Manager > Package Manager Console
-
Run
Install-Package Microsoft.EntityFrameworkCore.SqlServer
We will be using some Entity Framework Tools to create a model from the database. So we will install the tools package as well:
- Run
Install-Package Microsoft.EntityFrameworkCore.Tools
We will be using some ASP.NET Core Scaffolding tools to create controllers and views later on. So we will install this design package as well:
- Run
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
4. 修改startup.cs,用依賴注入注冊數據庫類
修改配置文件Startup.cs.
- 打開
Models\BloggingContext.cs
- 刪除
OnConfiguring(...)
方法 - 增加如下方法: public BloggingContext(DbContextOptions<BloggingContext> options) : base(options) { }
- 打開 startup.cs 增加如下代碼:
using EFGetStarted.AspNetCore.ExistingDb.Models;
using Microsoft.EntityFrameworkCore;
用下面替換原同名方法:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connection = @"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
}
OK,大致搞定。 先編譯一下。
5. 創建一個控制器
在解決方案中右單擊 Controllers 文件夾,選擇 添加 -> 控制器... 選擇視圖使用 Entity Framework 的MVC控制器 單擊 確定
接着在彈出窗口中選擇 Model class 為 Blog , 上下文為 BloggingContext 點擊 確定
6. 運行程序
單擊 綠箭頭 運行,在出現的主頁的地址后加上 /Blogs 回車
基本搞定。
打開_layout.cshtml 替換
<a asp-area="" asp-controller="Blogs" asp-action="Index" class="navbar-brand">EFGetStarted.AspNetCore.ExistingDb</a>
中的Home 為 Blogs , 重新運行程序,單擊 EFGetstarted 進入編輯。