使用EF Core的Code First模式,通过迁移来同步数据库与模型.
环境:
JetBrains Rider
Window10
.NET5
一. 创建项目
-
使用
JetBrains Rider
创建一个web api项目 -
使用NuGet安装依赖包
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
-
Microsoft.EntityFrameworkCore.SqlServer
此依赖包根据使用的数据库安装相应的包, 这里使用的是SQL Server
-
创建数据库上下文
-
在项目中建立一个Data文件夹,创建一个类TestDBContext
using Microsoft.EntityFrameworkCore; namespace Test.Data { public class TestDBContext : DbContext { public TestDBContext(DbContextOptions<TestDBContext> options) : base(options){} } }
-
-
创建数据模型
-
在项目中建立一个Models文件夹,创建部门类Department, 员工类Personnel
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Test.Models { /// <summary> /// 部门类 /// </summary> public class Department { [Key] // 主键 [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //设置自增 public int Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } // Department 与 Personnel 一对多 public ICollection<Personnel> Personnels { get; set; } = new List<Personnel>(); } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Test.Models { /// <summary> /// 员工类 /// </summary> public class Personnel { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } public int Age { get; set; } [ForeignKey("Department")] // 外键 public int DepartmentId { get; set; } } }
-
-
在之前创建的数据库上下文TestDBContext中注册数据模型
using Microsoft.EntityFrameworkCore; using Test.Models; namespace Test.Data { public class TestDBContext : DbContext { public TestDBContext(DbContextOptions<TestDBContext> options) : base(options){} // 注册数据模型 // 模型集的名称与对应的表名相同 public DbSet<Department> Departments { get; set; } public DbSet<Personnel> Personnels { get; set; } } }
-
在appsettings.json中添加数据库连接字符串
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "connectionStrings": { "SqlServerContext": "Data Source=服务器名;Initial Catalog=数据库名; User Id=用户名;Password=密码" } }
-
在Startup中注册数据库上下文TestDBContext
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Test.Data; namespace Test { public class Startup { // 注入 IConfiguration:有关配置文件最底层的一个接口类型 public Startup(IConfiguration configuration) { _Configuration = configuration; } private IConfiguration _Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "Test", Version = "v1"}); }); // 注册数据库上下文 // _Configuration["connectionStrings:SqlServerContext"] 获取数据库连接字符串 services.AddDbContext<TestDBContext>(option => option.UseSqlServer(_Configuration["connectionStrings:SqlServerContext"])); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
-
迁移
- 打开Terminal窗口或者cmd进入项目根目录执行迁移命令:
dotnet ef migrations add 本次迁移的名称
- 如果未安装
dotnet ef
, 会无法执行 - 安装全局
dotnet ef
- 再次执行迁移命令
- 迁移成功后, 项目中有一个Migrations目录, 保存着每次迁移的记录
- 打开Terminal窗口或者cmd进入项目根目录执行迁移命令:
-
更新数据库
- 执行
dotnet ef database update
- 数据库更新成功, 数据库就已经创建好了
- 当数据模型发生改变时, 只用再次执行迁移/更新数据库
- 执行
二. 添加初始数据
-
在数据上下文TestDBContext中重写OnModelCreating方法
using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Test.Models; namespace Test.Data { public class TestDBContext : DbContext { public TestDBContext(DbContextOptions<TestDBContext> options) : base(options){} // 注册数据模型 // 模型集的名称与对应的表名相同 public DbSet<Department> Departments { get; set; } public DbSet<Personnel> Personnels { get; set; } // 控制数据库和模型映射, 通过它可以自定义映射关系 protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Department>() .HasData(new List<Department>() { new Department() {Id = 1, Name = "人力资源部"}, new Department() {Id = 2, Name = "技术部"} }); modelBuilder.Entity<Personnel>() .HasData(new List<Personnel>() { new Personnel() {Id = 1, Name = "张三", Age = 23, DepartmentId = 2}, new Personnel() {Id = 2, Name = "李四", Age = 20, DepartmentId = 1}, new Personnel() {Id = 3, Name = "王五", Age = 25, DepartmentId = 2} }); base.OnModelCreating(modelBuilder); } } }
-
迁移, 更新数据库