// 建立MvcWEB項目
建立Models Controllers Views檔案夾 已有的不需添加
// 1. 安裝相關Nuget包
// a. Install - Package Microsoft.EntityForameWorkCore
// b . Sql Server Database Provider
// Install - Package Microsoft.EntityFrameworkCore.SqlServer
下面開始會有兩種方式 建立 一種在添加控制器的時候自動生成,另一種自己設定生成配置及連接配接字元串
第一種:
1 .在Models檔案夾中添加MyDBContext.cs 上下文類
附代碼:
public class MyDBContext:DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Auther> Authers { get; set; }
public MyDBContext(DbContextOptions<MyDBContext> options):base(options) {
}
//重寫OnConfiguring方法,配置資料庫連接配接(可選)
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
// optionsBuilder.UseSqlServer(@"Server=.;Database=BooksDB ;Trusted_Connection=True;");
//}
}
public class Book {
public int BookID { get; set; }
public int AutherID { get; set; }
public string Name { get; set; }
public DateTime DateTime { get; set; }
public string Content { get; set; }
public Auther Auther { get; set; }
}
2 .在Startup.cs檔案中注冊添加上下文:
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;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//dotnet add package Microsoft.EntityFrameworkCore.SqlServer (--version 2.2.4 可省略)
var a = Configuration["Message"];
var b = Configuration.GetConnectionString("Person:name");
var c = Configuration.GetSection("Logging");
// 下面為添加注冊連接配接服務
services.AddDbContext<MyDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultStr")));
}
3. 配置sppsettings.json檔案的連接配接字元串
localdb的自帶資料庫
"ConnectionStrings": {
"StudyCoreMvcContext": "Server=(localdb)\\mssqllocaldb;Database=StudyCoreMvcContext-ef441ba8-6874-4567-a570-89a7afbb147a;Trusted_Connection=True;MultipleActiveResultSets=true"
}
SQLserver連接配接
"ConnectionStrings": {
"DefaultStr": "Server=.;Database=BooksDB;Trusted_Connection=True;"
}
4 . 進行資料遷移:Migration
打開 VS 工具 - > NuGet軟體包管理器 - >軟體包管理器控制台
建立模型的初始表 :輸入指令 或者使用NuGet視圖安裝
Add-Migration InitialCreate
将新遷移應用于資料庫
Update-Database
系統會自動建立Migration 檔案夾
或者使用 dotnet CLI 工具指令建立
在vs中右鍵項目-》在資料總管中打開檔案-》點選src路徑檔案夾-》找到對應的項目檔案夾-》按住鍵盤Shift+滑鼠右鍵項目檔案夾-》選擇在此處打開指令視窗,然後分别輸入如下指令:
dotnet ef migrations add Initial
dotnet ef database update
注意: 建立名稱不同的多個DBContext時候需要添加如下參數 cmd 指令行執行dotnet ef migrations add Initial -c DemoDbContext
如在原指令後加上代碼-c DbContext的檔案名,如下
執行指令生成建立的檔案
dotnet ef migrations add Initial -c DemoDbContext
執行指令生成資料庫
dotnet ef database update -c DemoDbContext
NuGet可視化視圖界面安裝會出現搜不到任務包資源 請注意更換源位址設定
1.先檢查vs2017Nuget中搜尋看是否能搜尋到EntityFrameWorkCore 搜尋不到就需要配置Nuget資料源
位址:https://api.nuget.org/v3/index.json 并設定搜尋選項選擇第一個搜尋
指令執行完後生成目錄:裡面有建立資料表庫的sql腳本
5 .建立并打開Books控制器
CTOR 建立控制器構造函數中注入上下文
這裡我們利用ASP.NET Core的依賴注入來擷取資料庫上下文。
public readonly BooksDBContext myDBContext;
public BooksController(BooksDBContext _myDBContext)
{
myDBContext = _myDBContext;
//myDBContext = new MyDBContext();//不需要 不然得傳參數op
}
至此 以上第一種遷移連接配接資料庫CodeFirst已經完成
第二種自動連接配接配置資料庫方式 适用于WEBAPI ASP.NETCORE MVC EF
- 在Models目錄下建立BooksModels檔案夾 并建立類Book.cs
随便添加幾個屬性:
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string Content { get; set; }
}
2 .在控制器中右鍵點選添加控制器:
先添加紅色的 模型就選Book.cs類
之後上下文建立一個點選添加 如圖:
如果連接配接字元串是已有資料庫則直接可啟動檢視 因為新增的控制器中添加了Mvc的增删改查方法
如果選擇的是API控制器建立 則是WEB API的一套
如果配置的appsettings.json中連接配接字元串資料庫及表不存在
則使用資料遷移指令 打開項目網站根目錄進入cmd 執行以下指令:
Add-Migration InitialCreate
将新遷移應用于資料庫
Update-Database
系統會自動建立Migration 檔案夾
則會自動建立資料庫表字段
使用localDB vs自帶的資料庫則需要在Vs的視圖 sqlserver視圖資料總管打開連接配接檢視
往資料庫表中添加幾條資料測測 下面的是API
這是Books清單