1、安裝nuget包
Install-package Microsoft.EntityFrameworkCore Install-package Microsoft.EntityFrameworkCore.SqlServer
Install-package Microsoft.EntityFrameworkCore.Design
Micorsoft.EntityFrameworkCore:EF框架的核心包
Micorsoft.EntityFrameworkCore.SqlServer:針對SqlServer數據庫的擴展,使用SqlServer數據庫必須。類似的還有MySql,SqlLite等
Micorsoft.EntityFrameworkCore.ToolsMicorosft.EntityFrameworkCore.Design:用戶根據現有的數據庫生成模型代碼等
2、添加實體類
public class UserEntity { /// <summary> /// 自增Id /// </summary> [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key] public int EId { get; set; } public DateTime CreationTime { get; set; } = DateTime.Now; public DateTime UpdatTime { get; set; } = DateTime.Now; public Guid Gid { get; set; } public bool Deleted { get; set; } public string Name { get; set; } public string Pwd { get; set; } public string Email { get; set; } public DateTime RegistTime { get; set; } public DateTime LastLoginTime { get; set; } public bool Status { get; set; } }
3、增加數據庫上下文實體類
public class SQLDbContext : DbContext { public DbSet<UserEntity> userInfo; /// <summary> /// 注意要實現該構造 /// </summary> /// <param name="dbContext"></param> public SQLDbContext(DbContextOptions<SQLDbContext> dbContext) : base(dbContext) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer("Server=.;Database=WebSolution;User Id=sa;Password=Dbuser2015;", opt => { opt.CommandTimeout(1000); }); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<UserEntity>(u => { //設置表映射 u.ToTable("Users"); //設置索引 u.HasIndex(u => new { u.Name, u.Status }); }); } }
4、注入DbContext並添加鏈接字符串
public void ConfigureServices(IServiceCollection services) { //註冊數據庫上下文 services.AddDbContext<SQLDbContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("Main_ReadAndWrite")); }, ServiceLifetime.Scoped); }
"ConnectionStrings": { "Main_ReadAndWrite": "Server=.;Database=WebSolution;User Id=sa;Password=Dbuser2015;" }
5、初始化數據庫及更新
5.1首先需要安裝efcore 命令行工具
dotnet tool install --global dotnet-ef
如果需要更新命令行工具執行如下命令
dotnet tool update --global dotnet-ef
5.2生成、更新、刪除數據庫結構
1.生成 dotnet ef migrations add Initial --context Data.Model.SQLDbContext 2.更新到數據庫 dotnet ef database update 3.刪除 dotnet ef migrations remove
生成或更新後,ef會自動創建Migrations目錄用於記錄變動版本。
6、數據結構發佈
根據Migration的版本文件,可以自動創建數據庫結構升級sql語句。
dotnet ef migrations script 20201026033234_Initial -o init.sql
(注:可以指定項目和DbContext來應對多個context的情況)--startup-project ../D4L.Application --context D4L.Data.D4LDbContext
還可以根據代碼版本文件生成版本間的差異SQL
dotnet ef migrations script 20201026033234_Initial -o init.sql 20201026061627_Initial 20201026062005_UpUserAddDept
這樣就可以生成從20201026061627_Initial到20201026062005_UpUserAddDept之間的數據庫結構升級sql。