EntityFrameworkCore 根据实体类自动创建数据库
1.首先新建 Asp.Net Core WebApi 项目
2.添加一下引用 :
2.1 Pomelo.EntityFrameworkCore.MySql(我用的Mysql 根据自己情况引用就行)
2.2 Microsoft.EntityFrameworkCore
2.3 Microsoft.EntityFrameworkCore.Design
3.使项目支持dotnet ef 工具以使用Migrations
3.1 手动修改csproj文件(手动添加是因为在nuget添加Microsoft.EntityFrameworkCore.Tools.DotNet 时报错,估计是vs的问题),添加一下配置
<ItemGroup> <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" /> </ItemGroup>
4.打开CMD命令 cd到项目目录下(C:\Users\Administrator\source\repos\CodeFirst\CodeFirst),执行
dotnet build
Microsoft (R) Build Engine version 15.1.545.13942 Copyright (C) Microsoft Corporation. All rights reserved. Startup.cs(45,13): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. [C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo.csproj] EntityFrameworkCoreMigrationsDemo -> C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo\bin\Debug\netcoreapp1.0\EntityFrameworkCoreMigrationsDemo.dll Build succeeded. Startup.cs(45,13): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. [C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo.csproj] 1 Warning(s) 0 Error(s) Time Elapsed 00:00:04.76
5. 第4步完成后继续执行
dotnet ef
可以看见独角兽就说明引用成功了。距离胜利更近一步了
6.创建实例 StudentDbContext和相关实体类
using CodeFirst.Model.Entity; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace CodeFirst.Model.Db { public class StudentDbContext: DbContext { public StudentDbContext(DbContextOptions<StudentDbContext> options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql( @"Server=localhost;Port=3306;Database=Policy;UId=root;Pwd=mysql.com"); } public DbSet<Student> Student { get; set; } public DbSet<Teacher> Teacher { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace CodeFirst.Model.Entity { public class Student { [Key] public int Id { get; set; } public string Name { get; set; } public Teacher Teach { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace CodeFirst.Model.Entity { public class Teacher { public int Id { get; set; } public int Age { get; set; } public List<Student> Stus { get; set; } } }
7. 在Startup将StudentDbContext 注册为服务
8.使用Migrations 新建数据库初始化类DbInitializer
using CodeFirst.Model.Db; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace CodeFirst.Model { public class DbInitializer { public void InitializeAsync(StudentDbContext context) { //var migrations = await context.Database.GetPendingMigrationsAsync();//获取未应用的Migrations,不必要,MigrateAsync方法会自动处理 context.Database.MigrateAsync();//根据Migrations修改/创建数据库 } } }
9.在Startup.cs的Configure方法中,添加参数StudentContext context
,netcore会使用DI将DbContext注入到Configure方法,并添加对DbInitializer
的调用。
10.使用dotnet ef
命令创建Migrations:dotnet ef migrations add text text随便起名
C:\Users\Administrator\source\repos\CodeFirst\CodeFirst>dotnet ef migrations add Initial Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:02.32 Done. To undo this action, use 'ef migrations remove'
如果执行dotnet ef migrations add Initial报错 :

解决办法执行下面
定位到csproject
PM> dotnet ef migrations script --verbose -i --project "C:\Users\Administrator\source\repos\CodeFirst\CodeFirst"
完了继续操作就行
生成数据库表:
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
修改Student实体类加一个Sex字段
public string Sex { get; set; }
执行 (注意执行命令之前在控制台‘默认项目’列表选中DbContext所在的类库,不然爆错)
Add-Migration ModifyStudent
再执行
PM> Update-Database
数据库已经更新
Demo源码: Github
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?