Code First模式
Code First是指"代碼優先"或"代碼先行",
Code First模式將會基于撰寫的類和配置,自動創建模型和資料庫,
一、準備作業
創建一個(.NetCore 類別庫),命名為NetCoreWebApi.Model,
通過Nuget程式包安裝相關依賴
在類別庫專案上右鍵->管理NuGet程式包,下面會打開程式包管理器控制臺視窗:
注意版本,因為本人NetCore 是2.2版本,所以程式包都選擇了2.2.6

二、正式開始
根據.NET中的類來創建資料庫,
在類別庫專案上右鍵->添加->新建檔案夾,命名為Models,存放相應的物體類,在Models檔案夾下面新建物體類:tb_user,物體類的屬性如下:
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace NetCoreWebApi.Model.Models { /// <summary> /// 用戶表 /// </summary> [Table("tb_User")] public class TbUser { /// <summary> /// 用戶Id /// </summary> [Key] [Column("userId")] [StringLength(32)] public string UserId { get; set; } /// <summary> /// 用戶名 /// </summary> [Column("userName")] [StringLength(20)] public string UserName { get; set; } /// <summary> /// 郵箱 /// </summary> [Column("email")] [StringLength(30)] public string Email { get; set; } /// <summary> /// 創建時間 /// </summary> [Column("createTime")] public DateTime CreateTime { get; set; } } }
創建資料背景關系
在類別庫專案上右鍵->添加->類,命名為MyDbContext,并繼承DbContext類,DbContext位Microsoft.EntityFrameworkCore.dll程式集中,
using Microsoft.EntityFrameworkCore; using NetCoreWebApi.Model.Models; namespace NetCoreWebApi.Model { public class MyDbContext : DbContext { public MyDbContext() { } public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } //定義資料集合:用于創建表 public DbSet<TbUser> TbUsers { get; set; } } }
在appsettings.json中加入連接字串
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", //資料庫連接字串 "ConnectionStrings": { "SqlServer": "Data Source=.;Initial Catalog=NetCoreWebApi;User Id=sa;Password=123;" } }
在Startup.cs類ConfigureServices方法中添加EF的依賴
/// <summary> /// //負責注入服務 /// </summary> /// <param name="services"></param> /// <returns></returns> public void ConfigureServices(IServiceCollection services) { //獲取資料庫連接字串 var connectionStr = Configuration.GetConnectionString("SqlServer"); services.AddDbContext<MyDbContext> (options => options.UseSqlServer(connectionStr, e => e.MigrationsAssembly("NetCoreWebApi.Model"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
三、使用命令通過代碼生成資料庫
在程式包命令切換到NetCoreWebApi.Model中
先執行 Add-Migration InitialCreate
執行成功后會在專案中產生一個Migrations檔案夾,里面有個快照檔案和一個遷移的檔案,

后執行 Update-DataBase
出現這個就是成功了,
?
??
資料庫創建成功!
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/91639.html
標籤:.NET Core
上一篇:ASP.NET Core 2.2 WebApi 系列【一】搭建ASP.NET Core WebApi專案
下一篇:從零開始搭建前后端分離的NetCore2.2(EF Core CodeFirst+Autofac)+Vue的專案框架之十一Swagger使用一
