添加參考
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Tools
- Pomelo.EntityFrameworkCore.MySql
創建物體物件
這里創建兩個物體物件,順便演示添加外鍵的效果
public class TUser { public int ID { get; set; } public string UserName { get; set; } public string Password { get; set; } public ICollection<TRole> TRoles { get; set; } }
public class TRole { public int ID { get; set; } public string Name { get; set; } }
生成資料表時,屬性“ID”默認成為自增的主鍵,
上述兩個物體物件生成的資料表中,TRole中會包含TUser的外鍵,默認命名為TUserID,
創建背景關系物件
public class MyDbContext:DbContext { public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } public DbSet<TUser> Users { get; set; } public DbSet<TRole> Roles { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } }
將根據此檔案生成資料庫,把想要生成資料表的物體型別以上面代碼的形式作為屬性MyDbContext為自定義的資料庫背景關系名稱,由用戶自己起名,其他代碼可保持不變,
添加資料庫連接字串
在appsettings.json中加入連接字串(下方綠底部分):
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "MyDbContext": "server=localhost;database=MyDb;user=myUsername;password=myPwd;" } }
localhost替換為你的mysql地址,MyDb為將要生成資料表的資料庫名稱,myUsername為mysql的用戶名,myPwd為mysql的密碼,
添加資料背景關系服務
在StartUp類的ConfigureServices方法中添加如下代碼
services.AddDbContext<MyDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MyDbContext")));
此代碼將上面我們撰寫的MyDbContext這個類注冊為資料背景關系的服務,后續可通過DI方便地呼叫,Configuration.GetConnectionString(string name)獲取appsettings.json中“ConnectionStrings”這部分中對應名稱的字串,
生成資料庫
用vs2019的話,直接選單欄“工具”-NuGet包管理器-程式包管理器控制臺,
在打開的視窗中輸入如下兩個命令
- Add-Migration InitialCreate
- Update-Database
第一個命令會生成一個檔案,記錄所有我們代碼撰寫對資料庫的影響,生成的檔案自動放入Migrations檔案夾下,此檔案夾也自動生成,第一個命令中的“Initial Create”用來命名此次資料庫操作,可自己起名,
第二個命令將會根據第一個命令生成的遷移檔案對資料庫進行操作,
完成
此時,mysql資料庫中應該就可以看到TUser和TRole兩個資料表了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/100115.html
標籤:.NET Core
上一篇:SqlException:ConnectionTimeout Expired. The timeout period elapsed during the post-login phase
