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。