gpt4 book ai didi

c# - 如何向 __MigrationHistory 表添加附加列?

转载 作者:行者123 更新时间:2023-11-30 14:10:26 24 4
gpt4 key购买 nike

根据 Customizing the Migrations History Table ,我应该可以添加一列,但是我找不到任何关于如何实际添加新列的示例。

我最困惑的是将实际属性放在哪里以及如何将其配置到现有的 __MigrationHistory 表中。从文档中,我可以像这样自定义表配置..

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistory", schemaName: "admin");
modelBuilder.Entity<HistoryRow>().Property(p => p.MigrationId).HasColumnName("Migration_ID");
}

...但我无法修改 HistoryRow 实体。

我是否应该添加一个基于 HistoryRow 实体的新派生类型?

最佳答案

首先,您需要为历史记录行实体创建一个新类。例如:

public sealed class MyHistoryRow : HistoryRow
{
//We will just add a text column
public string MyColumn { get; set; }
}

接下来我们需要一个上下文,就像我们对普通 EF 操作所做的一样,但是这次我们继承自 HistoryContext:

public class MyHistoryContext : HistoryContext
{
//We have to 'new' this as we are overriding the DbSet type
public new DbSet<MyHistoryRow> History { get; set; }

public MyHistoryContext(DbConnection dbConnection, string defaultSchema)
: base(dbConnection, defaultSchema)
{
}

//This part isn't needed but shows what you can do
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

//Rename the table and put it in a different schema. Our new table
//will be called 'admin.MigrationHistory'
modelBuilder.Entity<MyHistoryRow>().ToTable(tableName: "MigrationHistory", schemaName: "admin");

//Rename one of the columns for fun
modelBuilder.Entity<MyHistoryRow>().Property(p => p.MigrationId).HasColumnName("Migration_ID");
}
}

现在要连接它们,我们需要配置它,所以首先我们设置配置:

public class MyConfiguration : DbConfiguration
{
public MyConfiguration()
{
//Set our new history context to be the one that gets used
this.SetHistoryContext("System.Data.SqlClient",
(connection, defaultSchema) => new MyHistoryContext(connection, defaultSchema));
}
}

最后,通过修改我们的 web.config 使配置生效:(您必须填写自己的命名空间和应用程序集:

<entityFramework codeConfigurationType="Namespace.MyConfiguration, ApplicationAssembly">
...snipped...
</entityFramework>

这样做的一个副作用是,如果/当您启用迁移时,您需要明确说明您正在使用的上下文。这显然是因为您现在在程序集中有两种上下文类型(除非您将它们分开。)所以您现在需要运行这样的命令:

enable-migrations -ContextTypeName Namespace.YourContextClass

关于c# - 如何向 __MigrationHistory 表添加附加列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24025075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com