【.Net core】EFCore——Code First生成数据库与表
Code First——領(lǐng)域設(shè)計(jì)模式中非常有用。使用 Code First 模式,專注于領(lǐng)域設(shè)計(jì),創(chuàng)建領(lǐng)域類,然后生成數(shù)據(jù)庫。
1.創(chuàng)建數(shù)據(jù)模型類
一般就是數(shù)據(jù)庫里面有哪些表,就創(chuàng)建哪些模型, POCO 類就夠了。
????public?partial?class?SmsPush{[Key]public?int?Id?{?get;?set;?}[MaxLength(128)]public?string?AppName?{?get;?set;?}[DataType(DataType.Text)]public?string?TargetValue?{?get;?set;?}[DataType(DataType.Text)]public?string?Content?{?get;?set;?}[DataType(DataType.DateTime)]public?DateTime?CreateTime?{?get;?set;?}}2.安裝 nuget 包
按您使用的數(shù)據(jù)選擇包
sqlserver:Install-Package Microsoft.EntityFrameworkCore.SqlServer
mysql:Install-Package MySql.Data.EntityFrameworkCore
3.創(chuàng)建數(shù)據(jù)庫上下文類
需要繼承DbContext
public?class?MvcMovieContext?:?DbContext{public?MvcMovieContext?(DbContextOptions<MvcMovieContext>?options):?base(options){}public?DbSet<Movie>?Movie?{?get;?set;?}}4.注冊數(shù)據(jù)庫上下文
在應(yīng)用啟動(dòng)過程中,EF core 數(shù)據(jù)庫上下文服務(wù)必須通過依賴注入注冊。需要服務(wù),通過構(gòu)造函數(shù)注入即可。
sqlserver
mysql
5.添加數(shù)據(jù)連接字符串
上面的Configuration.GetConnectionString,是從appsettings.json中讀取的。所以需要添加相關(guān)配置。由于使用的是 mysql,所以相關(guān)配置如下
{"ConnectionStrings":?{"PushContext":?"Persist?Security?Info=False;database=push-center;server=localhost;Connect?Timeout=30;user?id=root;?pwd=111111"} }mysql 鏈接字符串,參考 mysql 官方:https://dev.mysql.com/doc/dev/connector-net/8.0/html/P_MySql_Data_MySqlClient_MySqlConnection_ConnectionString.htm
6.安裝 Mysql
由于博主是在 windows 下開發(fā),所以這里介紹最簡單的 windows 下安裝 mysql 的方法及后續(xù)相關(guān)操作。這里我們推薦使用巧克力安裝 mysql,一款越用越香的 windows 包管理器,如果不知道巧克力,請參考博文【Nginx】Nginx 部署實(shí)戰(zhàn)——靜態(tài)文件+反向代理+均衡負(fù)載+https+websocket,有關(guān)于巧克力的安裝,可以類比 centos 的黃狗(yum).
#安裝mysql choco install mysql #遇到讓你選擇是否運(yùn)行腳本,Y/A 按著走有可能會(huì)遇到在https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.20-winx64.zip下載巨慢的情況(在公司下載很快,晚上在家下載很慢,不知道為啥,想辦法吧),可以在巧克力執(zhí)行powershell之前,也就是提示選擇他要執(zhí)行 C:\ProgramData\chocolatey\lib\mysql\tools\chocolateyInstall腳本,去編輯這個(gè)腳本,替換為國內(nèi)資源鏡像
不出意外,mysql就安裝好了,路徑C:\tools,甚至相關(guān) windows 服務(wù)也裝好了。根據(jù)之前的經(jīng)驗(yàn)【One by one 系列】一步步部署.Net core 應(yīng)用-CentOs 介紹的 mysql 安裝后,初始化密碼
# 修改密碼 # 初次安裝mysql,root賬戶沒有密碼。直接登錄 mysql -u root mysql>show databases; mysql>set password for 'root'@'localhost' =password('設(shè)置你的密碼'); Query OK, 0 rows affected (0.00 sec) #不需要重啟數(shù)據(jù)庫即可生效上面是針對 5.6 以下的版本有效,通過巧克力默認(rèn)安裝的是最新版本,是 8.0 版本,修改密碼的操作需要更換如下 sql 語句。
mysql -u root#初始化root賬戶的密碼 mysql>ALTER USER root@localhost IDENTIFIED BY '123456';7.初始遷移-Initial migration
運(yùn)用 efcore 遷移功能來創(chuàng)建數(shù)據(jù)庫。migration 是可用于創(chuàng)建和更新數(shù)據(jù)庫以匹配數(shù)據(jù)模型的一組工具
#第一步 Add-Migration InitialCreate#第二步 Update-DatabaseAdd-Migration InitialCreate:生成 Migrations/{timestamp}_InitialCreate.cs 遷移文件 。InitialCreate 參數(shù)是遷移名稱。可以使用任何名稱,但是按照慣例,會(huì)選擇可說明遷移的名稱。因?yàn)檫@是首次遷移,所以生成的類包含用于創(chuàng)建數(shù)據(jù)庫架構(gòu)的代碼。
Update-Database:將數(shù)據(jù)庫更新到上一個(gè)命令創(chuàng)建的最新遷移。此命令運(yùn)行在 Migrations/{time-stamp}_InitialCreate.cs 文件中 Up 方法,用于創(chuàng)建數(shù)據(jù)庫的。
ps:Up 方法創(chuàng)建 表。Down 方法可還原 Up 遷移所做的架構(gòu)更改。
如果是數(shù)據(jù)庫更新,會(huì)生成如下警告(可以忽略):
更多內(nèi)容參考:https://docs.microsoft.com/zh-cn/ef/core/miscellaneous/cli/powershell
8.依賴注入數(shù)據(jù)庫上下文
public?class?MoviesController?:?Controller {private?readonly?MvcMovieContext?_context;public?MoviesController(MvcMovieContext?context){_context?=?context;} }9.遷移回退
上面 migration 命令,主要依賴Microsoft.EntityFrameworkCore.Tools包,如果此包缺失,請安裝。
#先檢查下 Get-Help about_EntityFrameworkCore PM> Get-Help about_EntityFrameworkCore_/\__---==/ \\___ ___ |. \|\| __|| __| | ) \\\| _| | _| \_/ | //|\\|___||_| / \\\/\\TOPICabout_EntityFrameworkCoreSHORT DESCRIPTIONProvides information about the Entity Framework Core Package Manager Console Tools.LONG DESCRIPTIONThis topic describes the Entity Framework Core Package Manager Console Tools. See https://docs.efproject.net forinformation on Entity Framework Core.The following Entity Framework Core commands are available.Cmdlet Description-------------------------- ---------------------------------------------------Add-Migration Adds a new migration.Drop-Database Drops the database.Get-DbContext Gets information about a DbContext type.Remove-Migration Removes the last migration.Scaffold-DbContext Scaffolds a DbContext and entity types for a database.Script-DbContext Generates a SQL script from the current DbContext.Script-Migration Generates a SQL script from migrations.Update-Database Updates the database to a specified migration.SEE ALSOAdd-MigrationDrop-DatabaseGet-DbContextRemove-MigrationScaffold-DbContextScript-DbContextScript-MigrationUpdate-Database#上面是包沒問題的象征,如果有問題,再執(zhí)行如下命令 Install-Package Microsoft.EntityFrameworkCore.ToolsTo undo this action, use Remove-Migration.
# POCO類修改=>修改數(shù)據(jù)表 # 給本次遷移取一個(gè)名字:UpdateEditions,初始化取的名字:InitialCreate Add-Migration UpdateEditions# 更新 Update-Database# 突然發(fā)現(xiàn)可能有影響,那就回滾吧,刪除上一次遷移(回滾針對遷移進(jìn)行的代碼更改) Remove-MigrationRemove-Migration
| -Force | 恢復(fù)遷移(回滾應(yīng)用于數(shù)據(jù)庫的更改)。 |
參考鏈接
https://docs.microsoft.com/zh-cn/ef/core/miscellaneous/cli/powershell
https://docs.microsoft.com/zh-cn/ef/core/
https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-3.1&tabs=visual-studio
長按二維碼關(guān)注總結(jié)
以上是生活随笔為你收集整理的【.Net core】EFCore——Code First生成数据库与表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 跟我一起学Redis之高可用从主从复制开
- 下一篇: 龙芯.NET正式发布 开源共享与开发者共