[英]EF Core 2.1. Add custom column to MigrationHistory table
I use EF Core 2.1 Code-First. 我使用EF Core 2.1 Code-First。
SELECT * FROM [dbo].[__MigrationsHistory]
returns table from 2 columns SELECT * FROM [dbo].[__MigrationsHistory]
从2列返回表
I am looking for a way to add one more column AppliedOn
which will store the time when migration was really applied to database. 我正在寻找一种方法来添加一个AppliedOn
列,它将存储迁移实际应用于数据库的时间。
You could do that in SQL : 你可以在SQL中做到这一点:
alter table [dbo].[__MigrationHistory] add AppliedOn Datetime default getdate()
When EF applies a migration to the database it inserts a row in the table __MigrationHistory
. 当EF将迁移应用于数据库时,它会在表__MigrationHistory
插入一行。 This SQL Script adds the column AppliedOn
with a default value at getDate()
. 此SQL脚本在getDate()
AppliedOn
列添加为默认值。 When a row is inserted the column will contain the current datetime of this insert. 插入行时,该列将包含此插入的当前日期时间。
Or, you could do the same thing with an EF Migration : 或者,您可以使用EF Migration执行相同的操作:
By adding to the first migration(or to a new migration): 通过添加到第一次迁移(或新迁移):
public partial class Intial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "AppliedOnUtc",
schema: "Conversations",
table: "__MigrationsHistory",
defaultValueSql: "GETUTCDATE()"
);
}
....
}
There is an article from Microsoft here that indicates how to do this in a slightly more EF friendly fashion although they suggest a lot of caution as you could inadvertently break migrations. 有来自微软的文章在这里是指如何在一个稍微EF友好的方式做到这一点,尽管他们提出了很多特别小心,因为你可能无意中打破迁移。
This article only supports EF6.0 onwards which may be supported by EF Core 2.1 but I've not tried so I don't know whether it is available to you and the article is unclear on that. 本文仅支持EF6.0以上,EF Core 2.1 可能支持,但我没有尝试过,所以我不知道您是否可以使用它,文章也不清楚。
I totally get why you want to do it, but you could consider a custom patch table instead and insert into it from a Configuration.cs class when you create your code first migration. 我完全明白你想要这样做的原因,但你可以考虑使用自定义补丁表,并在创建代码第一次迁移时从Configuration.cs类插入。 Yes it's another step, yes it's not as elegant, but it might be safer from an EF standpoint. 是的,这是另一个步骤,是的,它不是那么优雅,但从EF的角度来看可能更安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.