EntityFramework Core 以下簡(jiǎn)稱 EF
使用VS 自帶的工具
下載 EntityFramework Core Tool
先使用Nuget包管理工具荧缘,搜索并下載EntityFramework Core Tool
image.png
搜索并下載安裝(各種同意就好了)
image.png
使用包管理工具,調(diào)用指令
前提: 代碼中先配置好师崎,要遷移的內(nèi)容,舉例可以參考尾部
- add-migration [名稱] 生成數(shù)據(jù)遷移指令
- update-database 執(zhí)行未執(zhí)行的遷移指令
- Drop-Database 刪除數(shù)據(jù)庫(kù)
- ... 更多參見(jiàn)文檔
使用命令行工具(跨平臺(tái)通用mac赎线,windows)
安裝 dotnet-ef
-
全局安裝 dotnet-ef 命令行工具
dotnet tool install --global dotnet-ef
image.png
執(zhí)行命令
我們可以先看看有哪些指令
image.png
可以看到有 添加蛉加,打包執(zhí)行抬闷,列出可用,移除少辣,具體有使用的時(shí)候可以百度或參考文檔凌摄,我這邊目前也沒(méi)有更多應(yīng)用,先把課程中展現(xiàn)的內(nèi)容復(fù)制出來(lái)
- 生成遷移文件
// 這里添加一個(gè) 【init】 為此次遷移的名稱
dotnet ef migrations add init
- 數(shù)據(jù)庫(kù)更新
dotnet ef database update
原理
image.png
由于漓帅, ef core tool 每次migrations 會(huì)生成對(duì)應(yīng)的 migrations 文件锨亏,一旦執(zhí)行update ,就像向數(shù)據(jù)庫(kù)中生成對(duì)應(yīng)記錄痴怨。
在執(zhí)行 database update 時(shí),會(huì)向數(shù)據(jù)庫(kù)中對(duì)比器予,migrations 文件夾中對(duì)應(yīng)的每個(gè) 遷移文件是否有執(zhí)行浪藻,這里類似如java 項(xiàng)目的 flyway
參考代碼
從Entity 初始化表結(jié)構(gòu)
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace xxx.API.Models
{
public class TouristRoute
{
// 指定主鍵
[Key]
public Guid Id { get; set; }
[Required]
[MaxLength(100)]
public string Title { get; set; }
[Required]
[MaxLength(1500)]
public string Description { get; set; }
[Column(TypeName ="decimal(18,2")]
public decimal OriginalPrice { get; set; }
[Range(0.0,1.0)]
public double? DiscountPresent { get; set; }
public DateTime CreateTime { get; set; }
public DateTime? UpdateTime { get; set;}
public DateTime? DePartureTime { get; set;}
[MaxLength]
public string Features { get; set; }
[MaxLength]
public string Fees { get; set; }
[MaxLength]
public string Note { get; set; }
/// <summary>
/// 一對(duì)多
/// </summary>
public ICollection<TouristRoutePictures> TouristRoutePictures { get; set; } = new List<TouristRoutePictures>();
}
}
從json初始化數(shù)據(jù)
注:以下代碼出自慕課.net core 開(kāi)發(fā)店商api
public class AppDbContext:DbContext
{
// *** 省略無(wú)關(guān)代碼
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var touristRoutesJsonData = File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"/Database/touristRoutesMockData.json");
IList<TouristRoute> touristRoutes = JsonConvert.DeserializeObject<IList<TouristRoute>>(touristRoutesJsonData);
modelBuilder.Entity<TouristRoute>().HasData(touristRoutes);
var touristRoutePicturesData = File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"/Database/touristRoutePicturesMockData.json");
IList<TouristRoute> touristRoutesPicture = JsonConvert.DeserializeObject<IList<TouristRoute>>(touristRoutePicturesData);
modelBuilder.Entity<TouristRoutePictures>().HasData(touristRoutesPicture);
base.OnModelCreating(modelBuilder);
}
}