简介
FluentMigrator 是一个开源的数据库迁移框架,可以帮助用户在开发过程中保持数据库的一致性。它提供了一个简洁的 Fluent API,可以让你使用 C# 写出简洁的迁移脚本。FluentMigrator 提供了一系列的 API 用来创建和管理数据库迁移,并且支持多种不同的数据库系统,包括 MySQL、PostgreSQL 和 SQL Server 等。.
使用 FluentMigrator 可以轻松地管理数据库迁移,这对于敏捷开发项目特别有用。比如,当开发团队的成员对数据库做出更改时,FluentMigrator 可以自动检测并应用这些更改,从而确保数据库保持一致性。
如何使用下面是一个示例,展示了如何在 .NET 中使用 FluentMigrator。
首先,创建一个控制台项目。
dotnet new console --name test
添加以下 Nuget 包, 这里我们使用了 SQLite 数据库。
dotnet add package FluentMigrator dotnet add package FluentMigrator.Runner dotnet add package FluentMigrator.Runner.SQLite dotnet add package Microsoft.Data.Sqlite
使用下面的代码创建一个迁移类,20220430_AddLogTable.cs, 这里我们使用了 Migration 特性指定了版本。
using FluentMigrator; namespace test { [Migration(20220430121800)] public class AddLogTable : Migration { public override void Up() { Create.Table("Log") .WithColumn("Id").AsInt64().PrimaryKey().Identity() .WithColumn("Text").AsString(); } public override void Down() { Delete.Table("Log"); } } }
这将会创建 Log 表和 ID , Text 列。
准备好迁移类后, 使用下面的代码,运行我们的迁移。
using System; using System.Linq; using FluentMigrator.Runner; using FluentMigrator.Runner.Initialization; using Microsoft.Extensions.DependencyInjection; namespace test { class Program { static void Main(string[] args) { var serviceProvider = CreateServices(); using (var scope = serviceProvider.CreateScope()) { UpdateDatabase(scope.ServiceProvider); } } private static IServiceProvider CreateServices() { return new ServiceCollection() .AddFluentMigratorCore() .ConfigureRunner(rb => rb .AddSQLite() .WithGlobalConnectionString("Data Source=test.db") .ScanIn(typeof(AddLogTable).Assembly).For.Migrations()) .AddLogging(lb => lb.AddFluentMigratorConsole()) .BuildServiceProvider(false); } private static void UpdateDatabase(IServiceProvider serviceProvider) { var runner = serviceProvider.GetRequiredService<IMigrationRunner>(); runner.MigrateUp(); } } }
运行上面的代码,程序会自动运行迁移,创建指定的 Log 表。
在进行多版本的更新后, 如何进行回滚呢,你可能已经注意到了, 上面的代码中我们实现 Down 方法, 删除了 Log 表。它表示,如果我们回滚到 Migration(20220430121800) 这个版本时,它会执行 Down 方法并删除 Log 表。
FluentMigrator 的主要优点在于它的易用性和灵活性。它的语法简洁明了,能够让开发人员快速编写数据库迁移脚本。此外,FluentMigrator 还支持在迁移过程中执行多种操作,包括创建表、添加字段、修改表结构等。
总之,FluentMigrator 是一款优秀的数据库迁移工具,能够为开发人员提供简洁、灵活的方式来管理数据库迁移。
项目地址:https://github.com/fluentmigrator/fluentmigrator