使用 DbUp 执行 C#(过程)迁移
Performing C# (procedural) migrations with DbUp
使用 DbUp,是否可以用 C#(而不是 SQL)编写过程迁移?
我意识到 DbUp 的一般理念是在 SQL 中完成所有事情,但在某些情况下,C# 可能是完成这项工作的更好工具。
例如,假设您在数据库中存储序列化的二进制 blob(忽略这是否是个好主意)并且您想要更改这些 blob 的结构。您的应用程序代码拥有 deserialize/serialize 这些 blob 的专业知识。通过 SQL 这样做可能 可能 ,但通过 C# 这样做会更简单。
有没有办法做到这一点(IScript
除外)?基本上我正在寻找一种机制
- 允许在事务上下文中对数据库发出任意命令
- 如果交易成功完成,则记录"migration"已完成
IScript
似乎是最接近的东西 - 想知道是否有更好的东西。
是 - 参见 https://dbup.readthedocs.io/en/latest/usage/#code-based-scripts
Code-based scripts Sometimes migrations may require more logic than is
easy or possible to perform in SQL alone. Code-based scripts provide
the facility to generate SQL in code, with an open database connection
and a System.Data.IDbCommand factory provided.
The code-based migration is a class that implements the IScript
interface. The ProvideScript() method is called when it is the
migration's turn to be executed, so the scripts before it have already
been executed.
Of course, the command factory can be used for more than just queries.
The entire migration itself can be performed in code:
public class Script0006UpdateInCode : IScript
{
public string ProvideScript(Func<IDbCommand> commandFactory)
{
var command = commandFactory();
command.CommandText = "CREATE TABLE [dbo].[Foo]( [Name] NVARCHAR(MAX) NOT NULL )";
command.ExecuteNonQuery();
return "";
}
}
使用 DbUp,是否可以用 C#(而不是 SQL)编写过程迁移?
我意识到 DbUp 的一般理念是在 SQL 中完成所有事情,但在某些情况下,C# 可能是完成这项工作的更好工具。
例如,假设您在数据库中存储序列化的二进制 blob(忽略这是否是个好主意)并且您想要更改这些 blob 的结构。您的应用程序代码拥有 deserialize/serialize 这些 blob 的专业知识。通过 SQL 这样做可能 可能 ,但通过 C# 这样做会更简单。
有没有办法做到这一点(IScript
除外)?基本上我正在寻找一种机制
- 允许在事务上下文中对数据库发出任意命令
- 如果交易成功完成,则记录"migration"已完成
IScript
似乎是最接近的东西 - 想知道是否有更好的东西。
是 - 参见 https://dbup.readthedocs.io/en/latest/usage/#code-based-scripts
Code-based scripts Sometimes migrations may require more logic than is easy or possible to perform in SQL alone. Code-based scripts provide the facility to generate SQL in code, with an open database connection and a System.Data.IDbCommand factory provided.
The code-based migration is a class that implements the IScript interface. The ProvideScript() method is called when it is the migration's turn to be executed, so the scripts before it have already been executed.
Of course, the command factory can be used for more than just queries. The entire migration itself can be performed in code:
public class Script0006UpdateInCode : IScript { public string ProvideScript(Func<IDbCommand> commandFactory) { var command = commandFactory(); command.CommandText = "CREATE TABLE [dbo].[Foo]( [Name] NVARCHAR(MAX) NOT NULL )"; command.ExecuteNonQuery(); return ""; } }